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: XXXXXXXX # other: XXXX # # or: # # self: XXXX #other: XXXXXXXX # 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.""" # Two cases: # # self: XXXXXXXX # other: XXXX # # or: # # self: XXXX #other: XXXXXXXX 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) result_coeff[:len(self.coeff)] = self.coeff[:] for i in range(len(other.coeff)): result_coeff[i] -= other.coeff[i] return Polynomial(result_coeff) p1 = Polynomial([1, -1]) #p1 = 1-x p2 = Polynomial([0, 1, 0, 0, -6, -1]) #p2 = x - 6*x**4 -x**5 p3 = p1 + p2 #p3 = 1 - 6*x**4 -x**5 print(p3.coeff) p4 = p1-p2 # -1 - 2*x + 6*x**4 + x**5 [-1,-2,0,0,6,1] print(p4.coeff) """ Terminal> python polynomial_sub.py [1, 0, 0, 0, -6, -1] [1, -2, 0, 0, 6, 1] """