-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMathExpression.py
More file actions
87 lines (74 loc) · 2.67 KB
/
Copy pathMathExpression.py
File metadata and controls
87 lines (74 loc) · 2.67 KB
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
import Tokens
import StatusTypes
class MathExpression:
def __init__(self):
self.value = 0
self.status = StatusTypes.STATUS_OK
def evaluate(self, token_stream, varmap={}, e_type=Tokens.INT):
try:
stack = self.infixToPostfix(token_stream, varmap)
final_value = self.calculate(stack)
if e_type == Tokens.INT:
final_value = int(final_value)
return final_value
except IndexError:
self.status = StatusTypes.STATUS_MISSING_OPEN_PAR
return 0
except TypeError:
self.status = StatusTypes.STATUS_MISSING_CLOSE_PAR
return 0
except ZeroDivisionError:
self.status = StatusTypes.STATUS_ZERO_DIVISION
return 0
def calculate(self, stack):
values = []
for token in stack:
if token in ['+', '-', '*', '/', '%']:
right = values.pop()
left = values.pop()
if token == '+':
val = left + right
elif token == '-':
val = left - right
elif token == '*':
val = left * right
elif token == '/':
val = left / right
elif token == '%':
val = left % right
values.append(val)
else:
values.append(token)
return values[0]
def infixToPostfix(self, token_stream, varmap):
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["%"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
opStack = []
postfixList = []
for token, token_value in token_stream:
if (token == Tokens.IDENTIFIER):
postfixList.append(varmap[token_value]['value'])
elif (token == Tokens.INT):
postfixList.append(int(token_value))
elif (token == Tokens.FLOAT):
postfixList.append(float(token_value))
elif token == Tokens.PAREN_OPEN:
opStack.append(token_value)
elif token == Tokens.PAREN_CLOSE:
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not len(opStack) == 0) and \
(prec[opStack[-1]] >= prec[token_value]):
postfixList.append(opStack.pop())
opStack.append(token_value)
while not len(opStack) == 0:
postfixList.append(opStack.pop())
return postfixList