-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcalculator_stack.py
More file actions
148 lines (121 loc) · 3.9 KB
/
Copy pathcalculator_stack.py
File metadata and controls
148 lines (121 loc) · 3.9 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import unittest
class NotMatchError(RuntimeError):
pass
class Calculator(object):
opPool = set("+-*/")
digitPool = set("0123456789")
def __init__(self):
self.stack = list()
def compile(self, strs):
res = []
for s in self.parsedExpression(strs):
if isinstance(s, (int, float)):
res.append(s)
else:
if s == "(":
self.stack.append(s)
elif s == ")":
while True:
if len(self.stack) == 0:
raise NotMatchError("Brackets not match")
tmps = self.stack.pop()
if tmps == "(":
break
else:
res.append(tmps)
else:
while len(self.stack) > 0:
if self.prioprity(self.stack[-1]) >= self.prioprity(s):
res.append(self.stack.pop())
else:
break
self.stack.append(s)
while len(self.stack) > 0:
tmp = self.stack.pop()
if tmp not in self.opPool:
raise NotMatchError("Brackets not match", tmp)
res.append(tmp)
self.res = res
return self.res
def run(self):
if "res" in self.__dir__() and len(self.res) > 0:
res = self.res
stack = []
for e in res:
if isinstance(e, (int, float)):
stack.append(e)
else:
n1 = stack.pop()
n2 = stack.pop()
r = self._cal(e, n2, n1)
stack.append(r)
return stack.pop()
# i = 0
# while len(res) > 1:
# if res[i+2] in self.opPool:
# a, b, op = res.pop(i), res.pop(i), res.pop(i)
# tmpRes = self._cal(op, a, b)
# res.insert(i, tmpRes)
# i = 0
# else:
# i += 1
# return float(res[0])
def calculate(self, strs):
self.compile(strs)
return self.run()
def _cal(self, op, a, b):
if op == '+':
r = a + b
elif op == '-':
r = a - b
elif op == '*':
r = a * b
elif op == '/':
r = a / b
else:
raise RuntimeError("Unsupported operator")
return r
def parsedExpression(self, strs):
output = []
i = 0
while i < len(strs):
if strs[i] == " ":
i += 1
continue
elif strs[i] not in self.digitPool:
output.append(strs[i])
i += 1
else:
tmps = ""
while (i < len(strs)) and (strs[i] in self.digitPool):
tmps += strs[i]
i += 1
output.append(int(tmps))
return output
@staticmethod
def prioprity(op):
priority = 0
if op in {"+", "-"}:
priority = 1
elif op in {"*", "/"}:
priority = 2
return priority
def main():
expression = "2 * 3 / (25 - 1)+3 * ((4 - 1)"
cal = Calculator()
r = cal.calculate(expression)
print(expression, " -> ", r)
print(eval(expression) == r)
class test(unittest.TestCase):
def testEqual(self):
expression = "2 * 3 / (25 - 1)+3 * (4 - 1)"
cal = Calculator()
r = cal.calculate(expression)
self.assertAlmostEqual(r, 9.25)
def testNotMatchError(self):
expression = "2 * 3 / (25 - 1)+3 * ((4 - 1)"
cal = Calculator()
with self.assertRaises(NotMatchError):
_ = cal.compile(expression)
if __name__ == '__main__':
unittest.main()