Skip to content

Commit b6af3a6

Browse files
committed
pro4 solved
1 parent b836246 commit b6af3a6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

unit4/pro4.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from opus7.polynomialAsSortedList import PolynomialAsSortedList
2+
3+
class MultiplyPolynomial(PolynomialAsSortedList):
4+
5+
def __mul__(self, poly):
6+
result = MultiplyPolynomial()
7+
p1 = iter(self._list)
8+
term1 = self.nextTerm(p1)
9+
while term1 is not None:
10+
p2 = iter(poly._list)
11+
term2 = self.nextTerm(p2)
12+
temp_poly = MultiplyPolynomial()
13+
while term2 is not None:
14+
exponent = term1.exponent + term2.exponent
15+
coefficient = term1.coefficient * term2.coefficient
16+
tmp = self.Term(coefficient, exponent)
17+
temp_poly.addTerm(tmp)
18+
term2 = self.nextTerm(p2)
19+
result += temp_poly
20+
term1 = self.nextTerm(p1)
21+
22+
return result
23+
24+
# test (1+2x+x^2)*(1+x)
25+
m1 = MultiplyPolynomial()
26+
m1.addTerm(MultiplyPolynomial.Term(1,0))
27+
m1.addTerm(MultiplyPolynomial.Term(2,1))
28+
m1.addTerm(MultiplyPolynomial.Term(1,2))
29+
m2 = MultiplyPolynomial()
30+
m2.addTerm(MultiplyPolynomial.Term(1,0))
31+
m2.addTerm(MultiplyPolynomial.Term(1,1))
32+
33+
print m1*m2

0 commit comments

Comments
 (0)