Skip to content

Commit b836246

Browse files
committed
pro3 solved
1 parent 32f0a76 commit b836246

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

unit4/pro3.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
'''
2+
Consider the Polynomial class given in Program . Implement a method that computes the value of a polynomial, say p(x), for a given value of x. Hint: Use a visitor that visits all the terms in the polynomial and accumulates the result.
3+
'''
4+
5+
from opus7.polynomialAsOrderedList import PolynomialAsOrderedList
6+
from opus7.visitor import Visitor
7+
8+
class MyPoly(PolynomialAsOrderedList):
9+
10+
def poly(self, x):
11+
poly_visitor = PolyVisitor(x)
12+
self.accept(poly_visitor)
13+
return poly_visitor.sum
14+
15+
16+
class PolyVisitor(Visitor):
17+
18+
def __init__(self, x):
19+
self._x = x
20+
self._sum = 0
21+
22+
def visit(self, obj):
23+
self._sum += obj.coefficient * self._x ** obj.exponent
24+
25+
def getSum(self):
26+
return self._sum
27+
28+
sum = property(
29+
fget = lambda self: self.getSum())
30+
31+
my_poly = MyPoly()
32+
# test polynomial 1 + 2x + x^2
33+
term1 = MyPoly.Term(1, 0)
34+
term2 = MyPoly.Term(2, 1)
35+
term3 = MyPoly.Term(1, 2)
36+
my_poly.addTerm(term1)
37+
my_poly.addTerm(term2)
38+
my_poly.addTerm(term3)
39+
print my_poly.poly(6)

0 commit comments

Comments
 (0)