-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpret_tree.py
111 lines (86 loc) · 2.68 KB
/
interpret_tree.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
'''
Created on 27 nov 2012
@author: gustaf
from pythonds.basic.stack import Stack
from pythonds.trees.binaryTree import BinaryTree
def buildParseTree(fpexp):
fplist = fpexp.split()
pStack = Stack()
eTree = BinaryTree('')
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if i == '(':
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree = currentTree.getLeftChild()
elif i not in ['+', '-', '*', '/', ')']:
currentTree.setRootVal(int(i))
parent = pStack.pop()
currentTree = parent
elif i in ['+', '-', '*', '/']:
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
currentTree = currentTree.getRightChild()
elif i == ')':
currentTree = pStack.pop()
else:
raise ValueError
return eTree
pt = buildParseTree("( ( 10 + 5 ) * 3 )")
pt.postorder()
'''
class Node(object):
def __init__(self):
self.children = []
def add_child(self, obj):
self.children.append(obj)
def pop(self):
return self.children.pop()
def evaluate(self):
pass
def get_children(self):
return self.children
class Number(Node):
def __init__(self, value):
Node.__init__(self)
self.value = value
def evaluate(self, arg):
return self.value
class Variable(Node):
def __init__(self):
Node.__init__(self)
def evaluate(self, arg):
return arg
class Plus(Node):
def __init__(self):
Node.__init__(self)
def evaluate(self, arg):
return self.get_children()[0].evaluate(arg) + self.get_children()[1].evaluate(arg)
class Minus(Node):
def __init__(self):
Node.__init__(self)
def evaluate(self, arg):
return self.get_children()[0].evaluate(arg) - self.get_children()[1].evaluate(arg)
class Multiply(Node):
def __init__(self):
Node.__init__(self)
def evaluate(self, arg):
return self.get_children()[0].evaluate(arg) * self.get_children()[1].evaluate(arg)
class Divide(Node):
def __init__(self):
Node.__init__(self)
def evaluate(self, arg):
return self.get_children()[0].evaluate(arg) / self.get_children()[1].evaluate(arg)
four = Number(4)
x = Variable()
two = Number(2)
three = Number(3)
multi = Multiply()
tree = Plus()
tree.add_child(multi)
tree.add_child(three)
multi.add_child(two)
multi.add_child(x)
print tree.evaluate(3)