class Polynomial: """Class for dealing with polynomials""" def __init__(self, coefficients): self.coeff = coefficients.copy() while len(self.coeff)>0 and self.coeff[-1] == 0: self.coeff.pop() self.n = len(self.coeff) def __call__(self, x): """Evaluate the polynomial.""" s=0 for i,c in enumerate(self.coeff): s += c * x**i return s def __str__(self): s = [] for i,c in enumerate(self.coeff): if c != 0: s.append(f'{c}*x^{i}') result = " + ".join(s) if result == '': result = '0' return result def __add__(self, other): # Start with the longest list and add in the other if self.n > other.n: result_coeff = self.coeff.copy() for i in range(other.n): result_coeff[i] += other.coeff[i] else: result_coeff = other.coeff.copy() for i in range(self.n): result_coeff[i] += self.coeff[i] return Polynomial(result_coeff) def __sub__(self, other): if self.n > other.n: result_coeff = self.coeff.copy() for i in range(other.n): result_coeff[i] -= other.coeff[i] else: result_coeff = [] for i in other.coeff: result_coeff.append(-i) for i in range(self.n): result_coeff[i] += self.coeff[i] return Polynomial(result_coeff) def __mul__(self, other): c = self.coeff d = other.coeff result_coeff = [0 for i in range(self.n + other.n - 1)] for i in range(self.n): for j in range(other.n): result_coeff[i+j] += c[i]*d[j] return Polynomial(result_coeff) def differentiate(self): """Differentiate this polynomial in-place.""" for i in range(1, self.n): self.coeff[i-1] = i * self.coeff[i] del self.coeff[-1] def derivative(self): """Copy this polynomial and return its derivative.""" dpdx = Polynomial(self.coeff) dpdx.differentiate() return dpdx if __name__ == "__main__": p1 = Polynomial([1, -1]) print("p1:", p1) p2 = Polynomial([0, 1, 0, 0, -6, -1]) print("p2:", p2) p3 = p1 + p2 print("p1 + p2:", p3) p4 = p1*p2 print("p1 * p2:", p4) p5 = p2.derivative() print("dp2/dx:", p5)