https://docs.python.org/3/tutorial/classes.html
class Poly: def __eq__(self, other): # poly1 == poly2 return (self - other).is_zero() # it works when the substraction is defined def __ne__(self, other): # poly1 != poly2 return not self == other # There is a problem with <, <=, >, >=.
class Poly: def __add__(self, other): # poly1 + poly2 new_poly = Poly(0, max(len(self.data), len(other.data)) -1) for (i, c) in enumerate(self.data): new_poly.data[i] += c for (i, c) in enumerate(other.data): new_poly.data[i] += c return new_poly def __sub__(self, other): # poly1 - poly2 new_poly = Poly(0, max(len(self.data), len(other.data)) -1) for (i, c) in enumerate(self.data): new_poly.data[i] += c for (i, c) in enumerate(other.data): new_poly.data[i] -= c return new_poly def __mul__(self, other): # poly1 * poly2 new_poly = Poly(0, len(self.data) + len(other.data) -2) for (i, c) in enumerate(self.data): for (j, d) in enumerate(other.data): new_poly.data[i+j] += c * d return new_poly def __pos__(self): # +poly1 = (+1)*poly1 return self def __neg__(self): # -poly1 = (-1)*poly1 new_poly = Poly() new_poly.data = [-c for c in self.data] return new_poly poly1 = Poly(3, 5) poly2 = Poly(1, 2) assert poly1 == poly1 # testing comparisons assert poly1 != poly2 # testing comparisons assert poly1 * poly2 == Poly(3, 7) assert poly1.__mul__(poly2) == Poly(3, 7) assert Poly.__mul__(poly1, poly2) == Poly(3, 7)
class Poly: def __call__(self, x): # Horner, polynomials are callable now result = 0 for c in reversed(self.data): result = result * x + c return result def combine(self, other): # Horner new_poly = Poly() for c in reversed(self.data): new_poly = new_poly * other + Poly(c) return new_poly poly1 = Poly(3, 5) poly2 = Poly(1, 2) assert poly1(2) == 96 assert poly2(9) == 81 assert poly1.combine(poly2) == Poly(3, 10) # 3*(x^2)^5 = 3*x^10
Add new methods to the Poly class.
class Poly: def copy(self): pass # shallow copy def __pow__(self, n): pass # poly1 ** n, pow(poly1, n) def __len__(self): pass # len(poly1), the number of monomials def diff(self): pass # derivative def integrate(self): pass # indefinite integral