-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
basic-calculator.py
66 lines (65 loc) · 2.18 KB
/
basic-calculator.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
class Solution:
def eval(self, a, op, b):
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '/':
return int(a / b)
elif op == '*':
return a * b
def calculate(self, s: str) -> int:
s += " "
precedence = {
'*': 1,
'/': 1,
'+': 0,
'-': 0
}
brackets = {
'(': 1,
')': -1
}
numstack = []
opstack = []
chunk = ""
latestOpenBracket = True
for c in s:
if c == " " or c in precedence or c in brackets:
if len(chunk) > 0:
numstack.append(int(chunk))
chunk = ""
if c in brackets:
if brackets[c] == 1:
opstack.append('(')
latestOpenBracket = True
elif brackets[c] == -1:
latestOpenBracket = False
while opstack[-1] != '(':
currop = opstack.pop()
b = numstack.pop()
a = numstack.pop()
res = self.eval(a, currop, b)
numstack.append(res)
opstack.pop()
elif c in precedence:
if latestOpenBracket:
numstack.append(0)
while len(opstack) > 0 and precedence.get(opstack[-1], -1) >= precedence[c]:
currop = opstack.pop()
b = numstack.pop()
a = numstack.pop()
res = self.eval(a, currop, b)
numstack.append(res)
opstack.append(c)
latestOpenBracket = False
else:
chunk += c
latestOpenBracket = False
while len(opstack) > 0:
currop = opstack.pop()
b = numstack.pop()
a = numstack.pop()
res = self.eval(a, currop, b)
numstack.append(res)
return numstack[0]