""" Ex 7.25 of "A primer on..." Extend the Polynomial class with a __sub__ special method to make it support substraction. The representation of Polynomials as a class with the coefficients stored as a list is described in Section 7.3.7 of "A primer on..." and in Section 8.9 of "Introduction to scientific programming...". """ class Polynomial: 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 """approach is similar to the __add__ method, but must be modified slightly since the order matters in substraction.""" if len(self.coeff) > len(other.coeff): """self.coeff is longest, and we can simply copy that coefficient list and then loop through other.coeff and substract each element.""" coeffdiff = self.coeff[:] # copy! for i in range(len(other.coeff)): coeffdiff[i] -= other.coeff[i] else: """other is longest. We create a list of zeros having the same length as other.coeff, fill the first entries with values from self, and then substract each element of other.""" coeffdiff = [0] * len(other.coeff) #other is long for i in range(len(self.coeff)): coeffdiff[i] = self.coeff[i] for i in range(len(coeffdiff)): 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 def test_Polynomial(): p1 = Polynomial([1, -1]) p2 = Polynomial([0, 1, 0, 0, -6, -1]) computed = p1 - p2 expected_coeff = [1, -2, 0, 0, 6, 1] assert computed.coeff == expected_coeff if __name__ == '__main__': test_Polynomial() #demonstrate the use of the class p1 = Polynomial([1, -1]) print(p1) p2 = Polynomial([0, 1, 0, 0, -6, -1]) p3 = p1 + p2 print(p3.coeff) print(p3) p4 = p1 - p2 print(p4.coeff) # [1, -2, 0, 0, 6, 1] """ Terminal> python polynomial_sub.py 1 - x^1 [1, 0, 0, 0, -6, -1] 1 - 6*x^4 - x^5 [1, -2, 0, 0, 6, 1] """