From 4e2e417e5b0fb3085de65648d2310b2da170e31e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Kn=C3=BCttel?= Date: Sun, 24 Feb 2019 21:14:36 +0100 Subject: [PATCH] added exam exercise 26 --- exam/ex26/main.py | 13 ++++++++++ exam/ex26/polynomial.py | 55 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 exam/ex26/main.py create mode 100644 exam/ex26/polynomial.py diff --git a/exam/ex26/main.py b/exam/ex26/main.py new file mode 100644 index 0000000..c90d49e --- /dev/null +++ b/exam/ex26/main.py @@ -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) diff --git a/exam/ex26/polynomial.py b/exam/ex26/polynomial.py new file mode 100644 index 0000000..a0dcb62 --- /dev/null +++ b/exam/ex26/polynomial.py @@ -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)]) + +