class Polynomial:
def __init__(self, coef):
self.coef = coef[:]
while len(self.coef) > 1 and self.coef[0] == 0:
self.coef.pop(0)
self.deg = len(self.coef) - 1
def __str__(self):
st = "".join(f"{('+' if i > 0 else '') if c > 0 else '-'}{str(abs(c)) if abs(c) != 1 else ''}x^{self.deg - i}" for i, c in enumerate(self.coef[:-2]))
if self.deg > 0 and self.coef[-2] != 0:
st += f"{('+' if self.deg > 1 else '') if self.coef[-2] >= 0 else '-'}{str(abs(self.coef[-2])) if abs(self.coef[-2]) != 1 else ''}x"
if self.coef[-1] != 0 and self.deg > 0:
st += f"{('+' if self.deg > 0 else '') if self.coef[-1] >= 0 else '-'}{str(abs(self.coef[-1])) if abs(self.coef[-1]) != 1 else '1'}"
if self.deg == 0:
st += str(self.coef[0])
return st
def __add__(self, other):
deg = max(self.deg, other.deg)
cs, os = self.coef[::-1], other.coef[::-1]
add = [0] * (deg + 1)
for i in range(deg + 1):
add[i] = (cs[i] if i < len(cs) else 0) + (os[i] if i < len(os) else 0)
return Polynomial(add[::-1])
def __neg__(self):
return Polynomial([-c for c in self.coef])
def __sub__(self, other):
return self + (-other)
def __mul__(self, other):
if isinstance(other, int):
return Polynomial([other * c for c in self.coef])
else:
deg = self.deg + other.deg
return Polynomial([sum((self.coef[i] if i < self.deg + 1 else 0) * (other.coef[k - i] if k - i < other.deg + 1 else 0)for i in range(k + 1)) for k in range(deg + 1)])
def __rmul__(self, other):
if isinstance(other, int):
return Polynomial([other * c for c in self.coef])
else:
deg = self.deg + other.deg
return Polynomial([sum((self.coef[i] if i < self.deg + 1 else 0) * (other.coef[k - i] if k - i < other.deg + 1 else 0)for i in range(k + 1)) for k in range(deg + 1)])
def __pow__(self, exp):
assert isinstance(exp, int) and exp >= 0
r = Polynomial([1])
for _ in range(exp):
r = r * self
return r
def __divmod__(self, other):
q, r = Polynomial([0]), Polynomial(self.coef)
step = 0
while (r.deg != 0 or r.coef[0] != 0) and r.deg >= other.deg:
c = r.coef[0] // other.coef[0]
t = Polynomial([c if i == 0 else 0 for i in range(r.deg - other.deg + 1)])
q = q + t
r = r - t * other
return (q, r)
n = Polynomial([1, 0, -3, 2, 0, 1])
d = Polynomial([1, 0, 3, 2])
q, r = divmod(n, d)
print(q, r)
To embed this program on your website, copy the following code and paste it into your website's HTML: