You can not extend a lambda like this. The variable you use inside the lambda only exists in it - that is why you get the first error (NameError: global name 'x' is not defined.
on x**cofLen)
). If you supply a global x, this still wont work, because you can not add an integer to a lambda.
Instead of incrementally building a lambda, you can use a reversed list of coefficients and enumerate() them to get a solution. Enumerate gives you the index into the list which translates to the "power" of x you need. Solution composing the function and calculating one x
of it:
def pol(coeff,x):
"""Calculates the resulting tuple for a polynomial given as coeff list
anc calculates it at one point of x.
coeff is a list - most significant exponent first: [1,2,3] == x^2+2x+3 """
# create a textual representation
t = []
for idx,c in enumerate(coeff[::-1]):
if c != 0:
if idx == 0:
t.append(f"{c}")
else:
t.insert(0,f"{f'{c}*' if c != 1 else ''}x{'' if idx==1 else f'^{idx}'}")
# connect text-parts with '+' and fix '+-' to '-'
text = '+'.join(t).replace("+-","-")
# calculate the functions value
result = sum( x**idx*v for idx,v in enumerate(coeff[::-1]))
return text + f" (@ x={x}) ",result
for i in range(10):
print(*pol([3,1,-4,1,0,-10],i), sep=" ==> ")
Output:
3*x^5+x^4-4*x^3+x^2-10 (@ x=0) ==> -10
3*x^5+x^4-4*x^3+x^2-10 (@ x=1) ==> -9
3*x^5+x^4-4*x^3+x^2-10 (@ x=2) ==> 74
3*x^5+x^4-4*x^3+x^2-10 (@ x=3) ==> 701
3*x^5+x^4-4*x^3+x^2-10 (@ x=4) ==> 3078
3*x^5+x^4-4*x^3+x^2-10 (@ x=5) ==> 9515
3*x^5+x^4-4*x^3+x^2-10 (@ x=6) ==> 23786
3*x^5+x^4-4*x^3+x^2-10 (@ x=7) ==> 51489
3*x^5+x^4-4*x^3+x^2-10 (@ x=8) ==> 100406
3*x^5+x^4-4*x^3+x^2-10 (@ x=9) ==> 180863
How does the reverse enumeration work?
enumerate ([3, 1, -4, 1, 0, -10][::-1]) gives us:
# values -10 0 1 -4 1 3 -> v
# indexes 0 1 2 3 4 5 -> idx
which are then sum( x**idx*v for idx,v in enumerate(coeff[::-1]))
-ed.
Example for x==5
:
c idx v
5 ** 0 * -10 = -10
5 ** 1 * 0 = 0
5 ** 2 * 1 = 25
5 ** 3 * -4 = -500
5 ** 4 * 1 = 625
5 ** 5 * 3 = 9375 Total sum = 9515