-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0227_Basic_Calculator_II.py
48 lines (46 loc) · 1.43 KB
/
0227_Basic_Calculator_II.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
class Solution:
def calculate(self, s: str) -> int:
m_d = set(["*", "/"])
p_m = set(["+", "-"])
stack = []
nums_str = ""
for each_s in s:
if each_s == " ":
continue
if each_s in m_d or each_s in p_m:
nums = int(nums_str)
if stack and stack[-1] in m_d:
if stack[-1] == "*":
stack.pop()
stack[-1] = stack[-1] * nums
else:
stack.pop()
stack[-1] = int(stack[-1] / nums)
else:
stack.append(nums)
stack.append(each_s)
nums_str = ""
else:
nums_str += each_s
if stack:
if stack[-1] == "*":
stack.pop()
stack[-1] = stack[-1] * int(nums_str)
elif stack[-1] == "/":
stack.pop()
stack[-1] = int(stack[-1] / int(nums_str))
else:
stack.append(int(nums_str))
else:
stack.append(int(nums_str))
sol = stack[0]
index = 1
while index < len(stack):
sign = stack[index]
index += 1
if sign == "+":
sol += stack[index]
else:
sol -= stack[index]
index += 1
return sol