import numpy 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 X X # other: X 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): """Return self - other as Polynomial object. As for the add function above, we have two cases that must be treated separately: one where self.coeff is longer than other.coeff, one where other.coeff is longest. The difference from the __add__ method is that for subtraction the order matters, so the implementation must be slightly different """ #start with the simplest case, where self is longest: 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: #Here, the polynomial we subtract is the #longest, which requires some extra care: 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) def __str__(self): s = '' for i in range(0, len(self.coeff)): if self.coeff[i] != 0: s += ' + %g*x^%d' % (self.coeff[i], i) # Fix layout s = s.replace('+ -', '- ') s = s.replace('x^0', '1') s = s.replace(' 1*', ' ') s = s.replace('x^1 ', 'x ') #s = s.replace('x^1', 'x') # will replace x^100 by x^00 if s[0:3] == ' + ': # remove initial + s = s[3:] if s[0:3] == ' - ': # fix spaces for initial - s = '-' + s[3:] return s def simplestr(self): s = '' for i in range(0, len(self.coeff)): s += ' + %g*x^%d' % (self.coeff[i], i) return s def test_Polynomial(): #first choose and create a couple of polynomials: p1 = Polynomial([1, -1]) p2 = Polynomial([0, 1, 0, 0, -6, -1]) #test the __add__ method: p3 = p1 + p2 p3_exact = Polynomial([1, 0, 0, 0, -6, -1]) msg = 'p1 = %s, p2 = %s\np3=p1+p2 = %s\nbut wrong p3 = %s'%\ (p1, p2, p3_exact, p3) assert p3.coeff == p3_exact.coeff, msg # Note __add__ applies lists only, here with integers, so # == for comparing lists is not subject to round-off errors #test the new __sub__ method: p4 = p1 - p2 p4_exact = Polynomial([1,-2,0,0,6,1]) msg = 'p1 = %s, p2 = %s\np4=p1-p2 = %s\nbut wrong p4 = %s'%\ (p1, p2, p4_exact, p4) assert p4.coeff == p4_exact.coeff, msg if __name__ == '__main__': import sys if len(sys.argv) >= 2 and sys.argv[1] == 'verify': test_Polynomial()