简体   繁体   中英

How does enumerate work in polynomial function (Python)?

I am a Python beginner and a bit confused about enumerate function in summing the polynomial problem in the following SO thread:

Evaluating Polynomial coefficients

The thread includes several ways to solve the summing of polynomials. I understand the following version well:

def evalP(lst, x):
    total = 0
    for power in range(len(lst)):
        total += (x**power) * lst[power] # lst[power] is the coefficient
    return total

Eg if I take third degree polynomial with x = 2, the program returns 15 as I expected based on pen and paper calculations:

evalP([1,1,1,1],2)

Out[64]:
15

But there is another, neater version of doing this that uses enumerate function:

evalPoly = lambda lst, x: sum((x**power) * coeff for power, coeff in enumerate(lst))

The problem is that I just can't get that previous result replicated with that. This is what I've tried:

coeff = 1
power = 3
lst = (power,coeff)
x = 2
evalPoly(lst,x)

And this is what the program returns:

Out[68]:
5

Not what I expected. I think I have misunderstood how that enumerate version takes on the coefficient. Could anyone tell me how I am thinking this wrong?

The previous version seems more general as it allows for differing coefficients in the list, whereas I am not sure what that scalar in enumerate version represents.

You should call evalPoly with the same arguments as evalP , eg evalPoly([1,1,1,1],2)

When you call evalPoly([3,1],2) , it return 3*2^0 + 1*2^1 which equals 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM