"""
Ex 6.11 from A primer on ...
"""
#Dictionary representation of polynomial
#p = -3+2*x**3-x**5
p = {0: -3, 3: 2, 5: -1}
#Function for evaluating the polynomial in a point x
#See "Introduction to scientific...", page 107:
def eval_poly_dict(poly, x):
sum = 0.0
for power in poly:
sum += poly[power]*x**power
return sum
"""
diff(p) should differentiate the polynomial and
return the result as a dict. If, for instance,
we have
p = {0: -3, 3: 2, 5: -1} (= -3 + 2*x**3 - x**5)
the result of diff(p) should be
{2:6,4:-5} (6*x**2 - 5*x**4)
"""
def diff(p):
dp = {}
for j in p:
if j != 0:
dp[j-1] = j*p[j]
return dp
print(diff(p))
"""
Terminal> python poly_diff.py
{2: 6, 4: -5}
"""