For the sake of practice, I am trying to calculate the following mathematical expression:
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.
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?
CodePudding user response:
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])
CodePudding user response:
You can do it briefly with a list comprehension:
def f(x,y):
return [4 * (x ** 3) * yy - 2 * x * yy if yy <= 0
else 4 * (x ** 3) * yy 2 * x * yy for yy in y]
OR
def f(x, y)
return [4 * (x ** 3) * yy (int(yy > 0) - 0.5) * 4 * x * yy for yy in y]