import copy class Polynom(object): def __init__(self, coefficients=[], degree=(-1)): self.coeff = copy.deepcopy(coefficients) l = len(self.coeff) if (degree >= l): self.coeff += [0 for i in range(degree + 1 - l)] def deg(self): return len(self.coeff) - 1 def __getitem__(self, i): return self.coeff[i] def __setitem__(self, i, v): self.coeff[i] = v def trim(self): d = self.deg() i = d while i >= 0 and self[i] == 0: i -= 1 if i < d: del self.coeff[i+1:] return self def __add__(self, p): d = max(self.deg(), p.deg()) sum = Polynom(degree = d) for i in range(0, self.deg() + 1): sum[i] += self[i] for i in range(0, p.deg() + 1): sum[i] += p[i] return sum.trim() def __sub__(self, p): d = max(self.deg(), p.deg()) sum = Polynom(degree = d) for i in range(0, self.deg() + 1): sum[i] -= self[i] for i in range(0, p.deg() + 1): sum[i] -= p[i] return sum.trim() def __mul__(self, p): if self.deg() < 0 or p.deg() < 0: return Polynom() d = self.deg() + p.deg() prod = Polynom(degree = d) for i in range(0, self.deg() + 1): for j in range(0, p.deg() + 1): prod[i + j] += self[i]*p[j] return prod def __str__(self): if self.deg() < 0: return "0" d = self.deg() s = "" for i in range(d, -1, -1): if i < d: s += " + " s += str(self[i]) if i > 0: s += "x" if i > 1: s += "^" + str(i) return s def __repr__(self): return str(self)