-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluator.py
44 lines (34 loc) · 1.01 KB
/
evaluator.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
import tokenizer as tok
from pprint import pprint
def evaluate(tokens):
result = 0
i = 0
if type(tokens) is tok.Token:
return int(tokens.value)
while i < len(tokens):
if len(tokens[i:i+3]) == 1:
return evaluate(tokens[i])
lhs, op, rhs = tokens[i:i+3]
'''
print("====")
pprint(lhs)
print("====", op)
pprint(rhs)
print("====")
'''
if type(lhs) is list:
lhs = evaluate(lhs)
if type(rhs) is list:
rhs = evaluate(rhs)
lhs, rhs = int(lhs.value) if type(lhs) is tok.Token else lhs, \
int(rhs.value) if type(rhs) is tok.Token else rhs
if op.value == "+":
return int(lhs) + int(rhs)
elif op.value == "-":
return int(lhs) - int(rhs)
elif op.value == "*":
return int(lhs) * int(rhs)
elif op.value == "/":
return int(lhs) / int(rhs)
i += 1
return result