""" Ex 7.25 from A Primer on ... Add __sub__ special method to polynomial class """ class Polynomial: def __init__(self, coefficients): self.coeff = coefficients def __call__(self, x): """Evaluate the polynomial.""" s = 0 for i in range(len(self.coeff)): s += self.coeff[i]*x**i return s def __add__(self, other): """Return self + other as Polynomial object.""" # Two cases: # # self: X X X X X X X #other: X X X # # or: # # self: X X X #other: X X X X X X X # Start with the longest list and add in the other if len(self.coeff) > len(other.coeff): result_coeff = self.coeff[:] # copy! for i in range(len(other.coeff)): result_coeff[i] += other.coeff[i] else: result_coeff = other.coeff[:] # copy! for i in range(len(self.coeff)): result_coeff[i] += self.coeff[i] return Polynomial(result_coeff) def __sub__(self,other): if len(self.coeff) > len(other.coeff): result_coeff = self.coeff[:] # copy! for i in range(len(other.coeff)): result_coeff[i] -= other.coeff[i] else: result_coeff = [0]*len(other.coeff) for i in range(len(self.coeff)): result_coeff[i] = self.coeff[i] for i in range(len(other.coeff)): result_coeff[i] -= other.coeff[i] return Polynomial(result_coeff) p1 = Polynomial([1,1,1,1]) #1 + x + x**2 + x**3 p2 = Polynomial([0,1,2]) #x + 2*x**2 print(p1(0.5)) # = 1.875 print(p2(0.5)) # = 1.0 p3 = p1+p2 #= 1+2*x+3*x**2 +x**3 print(p3(1.0)) # = 7.0 p4 = p1-p2 print(p4(1.0)) """ Terminal> python Polynomial_sub.py 1.875 1.0 7.0 1.0 """