forked from vpavlenko/web-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolynomial.py
More file actions
71 lines (60 loc) · 1.52 KB
/
polynomial.py
File metadata and controls
71 lines (60 loc) · 1.52 KB
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
65
66
67
68
69
70
71
class Polynomial:
'''
Class for single-variable polynomials
>>> print(Polynomial({1: 1}))
x
>>> Polynomial({1: 1})
Polynomial({1: 1})
>>> print(Polynomial({1: 1}) + Polynomial({2: 2}))
2x^2 + x
>>> x = Polynomial({1: 1})
>>> print(x + Polynomial({1: 1}))
2x
>>> a = 3 * x ** 2 - 4 * x
>>> b = 5 * x ** 2 - 1
>>> print(a * b)
15x^4 - 20x^3 - 3x^2 + 4x
>>> print(a)
3x^2 - 4x
>>> print(b)
5x^2 - 1
>>> b[0]
-1
>>> b[1]
0
>>> b[2]
5
>>> c = 1 - x ** 2
>>> c(5)
-24
'''
def __init__(self, coefs):
self.d = {}
for power, coef in coefs.items():
if coef:
self.d[power] = coef
def derivative(self):
d = {power - 1: coef * power for power, coef in self.d.items()}
if -1 in d:
del d[-1]
return Polynomial(d)
def __str__(self):
return ' + '.join(['{0} * x ** {1}'.format(coef, power)
for power, coef in self.d.items()])
def __add__(self, y):
if not isinstance(y, Polynomial):
p = Polynomial(self.d)
p.d[0] = p.d.get(0, 0) + y
return p
else:
raise NotImplementedError()
def __sub__(self, y):
return self + -y
def __radd__(self, y):
return self + y
def __repr__(self):
return 'Polynomial({0})'.format(repr(self.d))
x = Polynomial({1: 1})
if __name__ == '__main__':
import doctest
doctest.testmod()