forked from themaskarjd/calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluators.py
executable file
·30 lines (28 loc) · 997 Bytes
/
evaluators.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
#Scott Snow
#Comp 141, Homework 7
#Python Calculator (calculator.py)
from expressionTree import NumberExpressionTree, OperatorExpressionTree
class Evaluators:
def __init__(self):
pass
def evaluate(self, root):
if isinstance(root, NumberExpressionTree):
return root.getNumber()
oper = root.getOperator()
if oper == '~':
return -1.0 * self.evaluate(root.right)
else:
leftChild = self.evaluate(root.left)
rightChild = self.evaluate(root.right)
if oper == '+':
return leftChild + rightChild
elif oper == '-':
return leftChild - rightChild
elif oper == '*':
return leftChild * rightChild
elif oper == '/':
try:
return leftChild / rightChild
except ZeroDivisionError:
return float('Inf')
return 0.0