Chris Schell - 1 year ago 76

Python Question

Ok, I do not think this question has been answered here before.

I am wondering exactly how Python is executing this for loop. FYI this is a part of lesson 2 from 6.00SC MIT OCW:

`def evaluate_poly(poly, x):`

""" Computes the polynomial function for a given value x. Returns that value.

Example:

>>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2

>>> x = -13

>>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2

180339.9

poly: tuple of numbers, length > 0

x: number

returns: float """

ans = 0.0

for i in xrange(len(poly)):

ans += poly[i] * (x ** i)

return ans

Can anybody explain to me how this for loop is executing line by line? I understand the i variable is created to run 5 times (the length of the poly tuple), in which ans is being updated each iteration. Where I get confused is the reassignment of i each time through.

The third time through ans = 0.0 + (5) * x**(2)

It seems to me that poly[i] is grabbing the indexed number (5), but then x is multiplied to the power of i, which is now the index position itself (2). Which is exactly what it's supposed to do, however I cannot understand how i can seemingly be both the indexed number and the indexed position.

I am new to programming so any info at all will be a tremendous help.

Thanks so much!

Answer Source

i is assigned to those numbers in the loop: 0,1,2,3,4 because xrange creates a range from 0 till the parameter minus 1. Parameter is len(poly) that returns 5 (the size of the array. Therefore i is assigned from 0 till 4(=5-1)

First iteration i equals 0:

poly[0] actually equals to the first element of poly (0.0)

The formula then becomes:

```
ans += poly[i] * (x ** i)
ans = ans + poly[i] * (x ** i)
ans = 0.0 + poly[0] * (-13 in the power of 0)
ans = 0.0 + 0.0 * (-13 in the power of 0)
ans = 0.0
```

Next iteration i equals 1:

```
ans = ans + poly[i] * (x ** i)
ans = 0.0 + poly[1] * (-13 in the power of 1)
ans = 0.0 + 0.0 * (-13 in the power of 1)
ans = 0.0
```

Next iteration i equals 2:

```
ans = ans + poly[i] * (x ** i)
ans = 0.0 + poly[2] * (-13 in the power of 2)
ans = 0.0 + 5.0 * (-13 in the power of 2)
```

Next iteration i equals 3:

```
ans = ans + poly[i] * (x ** i)
ans = 5.0 * (-13 in the power of 2) + poly[3] * (-13 in the power of 3)
ans = 5.0 * (-13 in the power of 2) + 9.3 * (-13 in the power of 3)
```

Last iteration i equals 4:

```
ans = ans + poly[i] * (x ** i)
ans = 5.0 * (-13 in the power of 2) + 9.3 * (-13 in the power of 3) + poly[4] * (-13 in the power of 4)
ans = 5.0 * (-13 in the power of 2) + 9.3 * (-13 in the power of 3) + 7.0 * (-13 in the power of 4)
```