-
Notifications
You must be signed in to change notification settings - Fork 0
/
math_node.py
96 lines (75 loc) · 2.59 KB
/
math_node.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
"""
CSCI-603 Parser Lab
Author: Sean Strout @ RIT CS
Author: Shweta Yakkali
Author: Aishwarya Desai
A math expression is of the prefix form:
'{operator} {left-expression} {right-expression}'
For example:
'+ 10 20'
'* 3 5'
'- 2 4'
'// 13 2'
'+ 2 * 8 7'
When emitted, the statement is converted into an infix string:
'(10 + 20)'
'(3 * 5)'
'(2 - 4)'
'(13 //2 )'
'(2 + (8 * 7))'
When evaluated, integer result is returned:
30
15
-2
6
58
A runtime exception is raised division by 0 is attempted:
'// 4 0' # error message: Division by zero error
"""
import runtime_error # runtime_error.RuntimeError
import pretee # pretee.PreTee.ADD_TOKEN, ...
class MathNode:
"""
A MathNode consists of:
:slot left: the left expression (LiteralNode, MathNode, VariableNode)
:slot right: the right expression (LiteralNode, MathNode, VariableNode)
:token: the character for the math operation (str)
"""
__slots__ = 'left', 'right', 'token'
def __init__(self, left, right, token):
"""
Initialize a MathNode.
:param left: the left expression (LiteralNode, MathNode, VariableNode)
:param right: the right expression (LiteralNode, MathNode, VariableNode)
:param token: the character for the math operation (str)
:return: None
"""
self.left=left
self.right=right
self.token=token
def emit(self):
"""
Returns a parenthesized string with the emits of the left and
right expressions, e.g.:
'({left-emit} {token} {right-emit})'
:return:
"""
return '(' + self.left.emit()+' '+self.token +' '+self.right.emit()+ ')'
def evaluate(self):
"""
Evaluates the math expression and returns the result.
:exception: raises a runtime_error.RuntimeError if division by zero
is attempted, with the message, 'Division by zero error'
:return: The result of performing the math operation (int)
"""
if self.token=='+':
return int(self.left.evaluate()) + int(self.right.evaluate())
elif self.token=='-':
return int(self.left.evaluate()) - int(self.right.evaluate())
elif self.token=='*':
return int(self.left.evaluate()) * int(self.right.evaluate())
elif self.token=='//':
x=(self.right.evaluate())
if int(x)==0:
raise runtime_error.RuntimeError('divide by zero')
return int(self.left.evaluate()) // int(self.right.evaluate())