Context: I’m trying to make make a function that will return the value of any given polynomial. So for polynomial(a), where a = [a0,a1,…,an] should return a function p so that p(x) is the polynomial a0x**n + a1x**(n-1)…+an.
This is what I have:
def polynomial(coefs):
def p(x):
res = 0
i = len(coefs)
for a in coefs[:-1]:
i -=1
res += a*x**i
res += coefs[-1]
return res
return p(x)
# Tests:
xx = [0, 1, 2, 3] # Valores de x a testar
r = polynomial([1, 2, 3])
print([r(x) for x in xx]) # should return [3, 6, 11, 18]
But I keep getting name 'x' is not defined. If I’m saving the polynomial function as r, then if we pass an argument such as r(2) shouldn’t it basically return p(2) which will in turn return the result?
Thank you in advance! Any help is welcome as I’m still learning python
Note: I’m aware the function isn’t perfect yet for the example I’m trying to achieve, but I’d simply like to retrieve the desired output first and then I’ll check the inner workings of the p(x) function again
>Solution :
You actually can simplify this using lambda expression, and end up with something like this
from typing import List, Callable
def polynomials(coefs: List[int]) -> Callable[[int], int]:
return lambda x: sum([coefs[len(coefs) - i - 1] * (x ** i) for i in range(len(coefs) - 1, -1, -1)])
function = polynomials([1, 2, 3]) # x^2 + 2x + 3
print(function(1)) # 6
print(function(2)) # 11