-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path224.py
More file actions
67 lines (60 loc) · 1.9 KB
/
224.py
File metadata and controls
67 lines (60 loc) · 1.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
class Solution:
def calculate(self, s: str) -> int:
priors = {
"+":1,
"-":1,
"*":2,
"/":2,
"-unary": 3
}
op_stack = []
args_stack = []
def get_num_and_new_i(s, i):
start = i
while i < len(s) and s[i].isdigit():
i += 1
num = int(s[start:i])
return i-1, num
def calc_prev_op():
op = op_stack.pop()
if op == "-unary":
res = -args_stack.pop()
else:
arg2 = args_stack.pop()
arg1 = args_stack.pop()
if op == "+":
res = arg1 + arg2
elif op == "-":
res = arg1 - arg2
elif op == "*":
res = arg1 * arg2
elif op == "/":
res = int(arg1 / arg2)
args_stack.append(res)
prev_start_op = True
i = 0
while i < len(s):
c = s[i]
if prev_start_op and c == "-":
c = "-unary"
if c in priors:
while len(op_stack)>0 and op_stack[-1] != "(" and priors[op_stack[-1]] >= priors[c]:
calc_prev_op()
op_stack.append(c)
prev_start_op = True
elif c == "(":
op_stack.append(c)
prev_start_op = True
elif c == ")":
while op_stack[-1] != "(":
calc_prev_op()
op_stack.pop()
prev_start_op = False
elif c.isdigit():
i, num = get_num_and_new_i(s, i)
args_stack.append(num)
prev_start_op = False
i += 1
while len(op_stack) > 0:
calc_prev_op()
return args_stack[0]