-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.py
80 lines (66 loc) · 1.97 KB
/
interpreter.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
'''
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, data):
self.data = data
self.children = []
def add_child(self, obj):
self.children.append(obj)
def set_data(self, data):
self.data = data
def pop(self):
return self.children.pop()
class Expression:
def __init__(self):
pass
def evaluate(self):
pass
class Number(Expression):
def __init__(self, value):
self.value = value
def evaluate(self):
return self.value
class Plus(Expression):
def __init__(self, left, right):
self.left = left
self.right = right
def evaluate(self):
return self.left.evaluate() + self.right.evaluate()
one = Node(Number(1))
two = Node(Number(2))
tree = Node(None)
tree.add_child(one)
tree.add_child(two)
tree.set_data(Plus(tree.pop().data, tree.pop().data))
print tree.data.evaluate()