added exam exercise 26

This commit is contained in:
Daniel Knüttel 2019-02-24 21:14:36 +01:00
parent 682537589d
commit 4e2e417e5b
2 changed files with 68 additions and 0 deletions

13
exam/ex26/main.py Normal file
View File

@ -0,0 +1,13 @@
from polynomial import Polynomial
p1 = Polynomial([0, 2, 3, 4, 0, 0, 9])
p2 = Polynomial([0, 0, 1])
p3 = Polynomial([1, 0, 0, 1])
print("p1 = ", p1)
print("p2 = ", p2)
print("p3 = ", p3)
print("p1 + p3 = ", p1 + p3)
print("p2 * p3 = ", p2 * p3)
print("p1 * p3 = ", p1 * p3)

55
exam/ex26/polynomial.py Normal file
View File

@ -0,0 +1,55 @@
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)])