Q2.4.2Using a list to represent a polynomial
A list could be used as a simple representation of a polynomial, \(P(x)\), with the items as the coefficients of the successive powers of \(x\), and their indexes as the powers themselves. Thus, the polynomial \(P(x) = 4 + 5x + 2x^3\) would be represented by the list [4, 5, 0, 2]. Why does the following attempt to differentiate a polynomial fail to produce the correct answer?
>>> P = [4, 5, 0, 2]
>>> dPdx = []
>>> for i, c in enumerate(P[1:]):
... dPdx.append(i*c)
>>> dPdx
[0, 0, 4] # wrong!
How can this code be fixed?
Show solution
The problem is that enumerate, by default, returns the indexes and items of the array passed to it with the indexes starting at 0. The array passed to it is the slice P[1:] = [5, 0, 2] and so enumerate generates, in turn, the tuples (0, 5), (1, 0) and (2, 2). However, for our derivative we need the indexes into the original list, P, giving (1, 5), (2, 0) and (3, 2). There are two alternatives: pass the optional argument start=1 to enumerate or add 1 to the default index:
>>> P = [4, 5, 0, 2]
>>> dPdx = []
>>> for i, c in enumerate(P[1:], start=1):
... dPdx.append(i*c)
>>> dPdx
[5, 0, 6]
>>> P = [4, 5, 0, 2]
>>> dPdx = []
>>> for i, c in enumerate(P[1:]):
... dPdx.append((i+1)*c)
>>> dPdx
[5, 0, 6]