Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

function does't return a list as indented, but returns only one listelement instead

For the sake of practice, I am trying to calculate the following mathematical expression:

enter image description here

The x-value in the parameter is supposed to be a number – an int or float
The y-value in the parameter is supposed to be a list of numbers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The function is supposed to return a list of values in the same length as the list y in the parameter.

For some embarrassing reason, I only manage to make the function return only one list element, that comes from the first of the two equations in the function.

The code in question is:

def f(x ,y):

    list = []

    for i in y:
        if y[i] <= 0:
            list.append(4 * (x ** 3) * y[i] - 2 * x * y[i])
        if y[i] > 0:
            list.append(4 * (x ** 3) * y[i] + 2 * x * y[i])

        return list

x_value = 2
y_values = [1,-2, 3, -7]

print(f(x_value, y_values))

#wanted output: [28, -56, 85, -252]

#actual output: [-56]

My question is:

  • How do you make this function return a list with all the calculations? Like for example
    [28, -56, 85, -252] instead of the current output which is [-56]

This is probably an easy fix, but for some reason I am stuck.

Is there anybody kind enough to help me sort this out?

>Solution :

First, when you have for i in y, i is the actual value in y, not the index, so you don’t use y[i], you use i directly. Second, you should return the final list after the for i in y loop is over, so it needs to be outside the loop. And finally, don’t use built-in names (such as list) as your own variable/function/class names, because it will overwrite the built-in names.

def f(x ,y):
    L = []

    for i in y:
        if i <= 0:
            L.append(4 * (x ** 3) * i - 2 * x * i)
        if i > 0:
            L.append(4 * (x ** 3) * i + 2 * x * i)

    return L

To use i as an index, you need to change the loop to for i in range(len(y)), and use y[i] as you did previously.

Also, if you use numpy, you can solve this as:

>>> import numpy as np

>>> x_value = 2
>>> y_values = np.array([1,-2, 3, -7])

>>> 4 * x_value**3 * y_values + 2 * x_value * np.where(y_values <= 0, -y_values, y_values)
array([  36,  -56,  108, -196])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading