Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 13 Online
OpenStudy (anonymous):

Could someone fully explain what the following code does, step by step? def evaluate_poly(poly, x): sumPoly = 0 for i in range(0,len(poly)): #calculate each term and add to sum. sumPoly = sumPoly + (poly[i]*x**i) print sumPoly NOTE: Taken from solutions to Problem Set 2, Problem 1.

OpenStudy (anonymous):

Sure. A polynomial is basically the sum of a bunch of x terms (with coefficients) to various degrees. Take the polynomial 5 + 3x + 2x^2. Notice how it's 5 times x^0 + 3 times x^1 + 2 times x^2. The degrees are steadily going up. The function represents a polynomial by coefficients in certain places in a list. The polynomial above would be represented by [5,3,2] because 5 is in the 0th place, 3 is in the 1st place, and 2 is in the 2nd, corresponding to their respective degrees. The function works like this: It first creates a variable called sumPoly, initially set to 0, that will keep getting larger and larger as more things are added to it and will eventually hold the entire sum. Creating these variables that hold a running total is so common in programming, it's not even funny...get used to doing this a lot. Then, a for loop walks through every element in the polynomial. Notice we're not actually walking through the elements, we're walking through the indices (0 through however long the polynomial is) because we need the indices to raise x to that power. It calculates what x to that power is, and then adds that term of the polynomial to the running total. When it reaches the end of the polynomial, that means the sum is done, so the function prints the sum.

OpenStudy (anonymous):

Thank you!

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!