Issue
I would appreciate help on this.
I have a list of the form [-100,20,30,40,50]
.
I need to create a function of the form -100+20x+30x**2+40x**3+50x**5
.
I understand that some kind of a for-loop is needed in order to make the transformation, such as:
for i in range(len(lst)):
lambda x: sum(lst[i]*x**i)
output is as follows:
<function irr_newton.<locals>.<lambda> at 0x7fb98844ad30>
Solution
There numerous ways to do this. But if you want to use lambda, this is one way to do it.
coefs = [-100,20,30,40,50]
function = lambda x: sum([coef*x**i for i, coef in enumerate(coefs)])
Test:
function(2)
Output:
1180
Alternatively, you can go about it using a for loop:
def function(x):
coefs = [-100,20,30,40,50]
result = 0
for i, num in enumerate(coefs):
result += num*x**i
return result
I thought of one more solution, where you use a recursive function.
coefs = [-100,20,30,40,50]
def function(x):
if coefs == []:
return 0
result = coefs.pop(-1)*x**(len(coefs))
return function(x) + result
Answered By - Emmanuel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.