""" Ex. 7.25 from "A primer on..." Add a special method for subtraction to the Polynomial class. The method we need to implement is __sub__. The implementation will be similar to __add__, but with the important difference that for subtraction the order of the two arguments matters. """ class Polynomial: """ class implementation of a polynomial, using a list to represent the polynomial coefficients. """ def __init__(self, coefficients): self.coeff = coefficients def __call__(self, x): s = 0 for i in range(len(self.coeff)): s += self.coeff[i]*x**i return s def __add__(self, other): # return self + other # Two cases: # # self: X X X X X # other: X X X X X X X X # # or: # # self: X X X X X X X # other: X X X # start with the longest list and add in the other: if len(self.coeff) > len(other.coeff): coeffsum = self.coeff[:] # copy! for i in range(len(other.coeff)): coeffsum[i] += other.coeff[i] else: coeffsum = other.coeff[:] # copy! for i in range(len(self.coeff)): coeffsum[i] += self.coeff[i] return Polynomial(coeffsum) def __sub__(self, other): #return self - other #if self is longest we can use the same approach as #in the __add__ method. If other is longest we need a # slightly different approach if len(self.coeff) >= len(other.coeff): coeffdiff = self.coeff[:] # copy! for i in range(len(other.coeff)): coeffdiff[i] -= other.coeff[i] else: coeffdiff = [0] * len(other.coeff) coeffdiff[:len(self.coeff)] = self.coeff[:] for i in range(len(other.coeff)): coeffdiff[i] -= other.coeff[i] return Polynomial(coeffdiff) def __mul__(self, other): M = len(self.coeff) - 1 N = len(other.coeff) - 1 coeff = [0]*(M+N+1) # or zeros(M+N+1) for i in range(0, M+1): for j in range(0, N+1): coeff[i+j] += self.coeff[i]*other.coeff[j] return Polynomial(coeff) def differentiate(self): #in-place differentiation, changes self, for i in range(1, len(self.coeff)): self.coeff[i-1] = i*self.coeff[i] del self.coeff[-1] def derivative(self): # returns new polynomial, does not change self dpdx = Polynomial(self.coeff[:]) # copy dpdx.differentiate() return dpdx def __str__(self): s = '' for i in range(0, len(self.coeff)): if self.coeff[i] != 0: s += f' + {self.coeff[i]:g}*x^{i:g}' # fix layout (many special cases): s = s.replace('+ -', '- ') s = s.replace(' 1*', ' ') s = s.replace('x^0', '1') s = s.replace('x^1 ', 'x ') if s[0:3] == ' + ': # remove initial + s = s[3:] if s[0:3] == ' - ': # fix spaces for initial - s = '-' + s[3:] return s if __name__ == '__main__': # demonstrate the use of the method p1 = Polynomial([1, -1]) # = 1 - x print(p1) p2 = Polynomial([0, 1, 0, 0, -6, -1]) #= x - 6x^4 - x^5 print(p2) p3 = p1 - p2 #should give -1 - 2x + 6x^4+x^5 print(p3) """ Terminal> python Polynomial_sub.py 1 - x^1 1 - 2*x + 6*x^4 + x^5 """