Reputation: 275
Imagine I have a function like below:
f = (s**2 + 2*s + 5) + 1
where s is :
s = [1 , 2 , 3]
How can I pass the s to my function?
I know that I can define a function like below:
def model(s):
model = 1 + (s**2 + 2*s + 5)
return model
fitted_2_dis = [model(value) for value in s]
print ("fitted_2_dis =", fitted_2_dis)
To get :
fitted_2_dis = [9, 14, 21]
I prefer to not using this method. Because my actual function is so big with a lot of expressions. So, instead of bringing all the expressions in my code, I defined my function like below:
sum_f = sum (f)
Sum_f in my code is the summation of bunches of expressions.
Is there any other way to evaluate my function (sum_f) when the input is an array? Thanks
Upvotes: 0
Views: 49
Reputation: 11
You can try this:
import numpy as np
def sum_array(f):
np_s = np.array(f)
return (np_s**2 + 2*np_s + 5) + 1
s = [1, 2, 3]
sum_f = sum_array(s)
Upvotes: 1
Reputation: 2188
Map function will fulfill the task quite nicely:
>>> map(model, s)
[9, 14, 21]
Upvotes: 1
Reputation: 13498
The list comprehension method is a great method. Additionally you may also use map
:
fitted_2_dis = list(map(model, s))
If you're a numpy
fan you can use np.vectorize
:
np.vectorize(model)(s)
Finally if you convert your array to numpy
's ndarray
you an pass it in directly:
import numpy as np
s = np.array(s)
model(s)
Upvotes: 2