"""" Ex 7.25 from "A primer on... Implement a __sub__ special method to support subtraction of polynomials. The method can be based on the structure of the __add__ method, but some modifications are needed since the order of the arguments is not arbitrary in substraction. """ 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 # 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 len(self.coeff) > len(other.coeff): #copy self, subtract other coeffdiff = self.coeff[:] # copy! for i in range(len(other.coeff)): coeffdiff[i] -= other.coeff[i] else: #other is longest, needs some care to avoid index error coeffdiff = [0] * len(other.coeff) #list of zeros, same length as other for i in range(len(self.coeff)): #fill first entries with values from self, rest remain zero coeffdiff[i] = self.coeff[i] for i in range(len(other.coeff)): #subtract coefficients from other coeffdiff[i] -= other.coeff[i] return Polynomial(coeffdiff) 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__': p1 = Polynomial([1, -1]) print(p1) p2 = Polynomial([0, 1, 0, 0, -6, -1]) p3 = p1 + p2 p4 = p2 - p1 print(p4.coeff) #[-1, 2, 0, , -6, -1] print(p4) print(p3.coeff) print(p3) print(p3(2.0)) """ Terminal> python Polynomial_sub.py 1 - x^1 [-1, 2, 0, 0, -6, -1] -1 + 2*x - 6*x^4 - x^5 [1, 0, 0, 0, -6, -1] 1 - 6*x^4 - x^5 -127.0 """