-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpolynomial.py
65 lines (43 loc) · 1.58 KB
/
polynomial.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from itertools import zip_longest
# strip all copies of elt from the end of the list
def strip(L, elt):
if len(L) == 0: return L
i = len(L) - 1
while i >= 0 and L[i] == elt:
i -= 1
return L[:i+1]
class Polynomial(object):
def __init__(self, coefficients):
self.coefficients = strip(coefficients, 0)
self.indeterminate = 'x'
def add(self, other):
newCoefficients = [sum(x) for x in zip_longest(self, other, fillvalue=0)]
return Polynomial(newCoefficients)
def __add__(self, other):
return self.add(other)
def multiply(self, other):
newCoeffs = [0] * (len(self) + len(other) - 1)
for i,a in enumerate(self):
for j,b in enumerate(other):
newCoeffs[i+j] += a*b
return Polynomial(strip(newCoeffs, 0))
def __mul__(self, other):
return self.multiply(other)
def __len__(self):
return len(self.coefficients)
def __repr__(self):
return ' + '.join(['%s %s^%d' % (a, self.indeterminate, i) if i > 0 else '%s'%a
for i,a in enumerate(self.coefficients)])
def evaluateAt(self, x):
theSum = 0
for c in reversed(self.coefficients):
theSum = theSum * x + c
return theSum
def __iter__(self): return iter(self.coefficients)
def __neg__(self): return Polynomial([-a for a in self])
def __sub__(self, other): return self + (-other)
def __abs__(self): return len(self.coefficients)
def __call__(self, *args): return self.evaluateAt(args[0])
if __name__ == "__main__":
f = Polynomial([1,2,3])
g = Polynomial([4,5,6])