-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path227.py
More file actions
67 lines (53 loc) · 1.39 KB
/
227.py
File metadata and controls
67 lines (53 loc) · 1.39 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
# 2+3*4^(2+2)-6*8
def calc(s):
priors = {
"+":1,
"-":1,
"*":2,
"/":2
}
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 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()
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)
i = 0
while i < len(s):
c = s[i]
if c in priors:
while len(op_stack)>0 and priors[op_stack[-1]] >= priors[c]:
calc_prev_op()
op_stack.append(c)
elif c.isdigit():
i, num = get_num_and_new_i(s, i)
args_stack.append(num)
i += 1
while len(op_stack) > 0:
calc_prev_op()
return args_stack[0]
if __name__ == '__main__':
print(calc("3+2*2"))
print(calc(" 3/2 "))
print(calc(" 3+5 / 2 "))