scientific-programming-exer.../exam/ex26/polynomial.py

56 lines
1.5 KiB
Python

from collections import defaultdict
class Polynomial(object):
__slots__ = ["koefficients"]
def __init__(self, koefficients):
self.koefficients = list(koefficients)
# Remove trailing zeros.
while(self.koefficients and self.koefficients[-1] == 0):
self.koefficients.pop()
def __call__(self, x):
if(not isinstance(x, (float, int, complex))):
raise TypeError("unsupported type for {}: {}".format(x, type(x)))
result = 0
for i, a in enumerate(self.koefficients):
result += a * x**i
return result
def __add__(self, other):
if(not isinstance(other, Polynomial)):
raise TypeError("cannot add {} and {}".format(type(self), type(other)))
p1 = self.koefficients
p2 = other.koefficients
if(len(other.koefficients) > len(self.koefficients)):
p1, p2 = p2, p1
p2 += [0] * (len(p1) - len(p2))
return Polynomial([a + b for a,b in zip(p1, p2)])
def __mul__(self, other):
if(isinstance(other, (int, float, complex))):
return Polynomial([a * other for a in self.koefficients])
if(not isinstance(other, Polynomial)):
raise TypeError("cannot add {} and {}".format(type(self), type(other)))
result = defaultdict(int)
for i, k1 in enumerate(self.koefficients):
for j, k2 in enumerate(other.koefficients):
result[i + j] += k1 * k2
return Polynomial(result[i] for i in range(max(result)))
def __repr__(self):
return "{}({})".format(type(self).__name__, self.koefficients)
def __str__(self):
return " + ".join(["{}*x**{}".format(a, i) for i, a in enumerate(self.koefficients)])