-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolynomial_algorithms.py
63 lines (53 loc) · 1.55 KB
/
polynomial_algorithms.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
def add(lst1, lst2, *, add, zero):
if len(lst1) < len(lst2):
(lst2, lst1) = (lst1, lst2)
lst = lst1[:]
for i, x in enumerate(lst2):
if x != zero:
if lst[i] == zero:
lst[i] = x
else:
lst[i] = add(lst[i], x)
return lst
def eval(lst, *, x, zero, add, mul, power):
result = zero
for degree, coeff in enumerate(lst):
if coeff != zero:
term = mul(coeff, power(x, degree))
result = add(result, term)
return result
def multiply(lst1, lst2, *, add, mul, zero):
def sum(x, y):
if x == zero:
return y
elif y == zero:
return x
else:
return add(x, y)
lst = [zero] * (len(lst1) + len(lst2) - 1)
for i, x in enumerate(lst1):
for j, y in enumerate(lst2):
xy = mul(x, y)
if xy != zero:
lst[i + j] = sum(lst[i + j], xy)
return lst
def stringify(lst, *, var_name, zero, one):
if len(lst) == 0:
return str(zero)
def monomial(coeff, i):
if i == 0:
return str(coeff)
elif i == 1:
if coeff == one:
return var_name
else:
return f"({coeff})*{var_name}"
else:
if coeff == one:
return f"{var_name}**{i}"
else:
return f"({coeff})*{var_name}**{i}"
terms = [
monomial(coeff, degree) for degree, coeff in enumerate(lst) if coeff != zero
]
return "+".join(reversed(terms))