-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path224.py
More file actions
executable file
·88 lines (87 loc) · 2.82 KB
/
224.py
File metadata and controls
executable file
·88 lines (87 loc) · 2.82 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
class Solution:
def calculate(self, s: str) -> int:
s = s.replace(' ','')
stack = []
for c in s:
if (c != ')'):
stack.append(c)
else:
tmp = 0
cur = stack.pop()
last = 0
while (cur != '('):
if (cur >= '0' and cur <= '9'):
tmp_s = cur
cur = stack.pop()
while (cur >= '0' and cur <= '9'):
tmp_s = cur + tmp_s
cur = stack.pop()
last = int(tmp_s)
else:
if (cur == '-'):
tmp -= last
else:
tmp += last
cur = stack.pop()
# (4 + ...)
tmp += last
if (tmp < 0):
if (len(stack) > 0):
tmp_c = stack.pop()
if (tmp_c == '+'):
stack.append('-')
else:
stack.append('+')
if (len(stack) == 0):
stack.append('-')
for c in str(tmp):
if (c == '-'):
continue
stack.append(c)
if (tmp == 0):
stack.pop()
if (tmp > 0):
for c in str(tmp):
stack.append(c)
if (len(stack) == 0):
return 0
#print(stack)
tmp = 0
cur = stack.pop()
last = 0
if (len(stack) == 0):
return int(cur)
flag = False
last_op = ""
while (True):
if (cur >= '0' and cur <= '9'):
tmp_s = cur
if (len(stack) == 0):
last_op = 'num'
last = int(tmp_s)
break
cur = stack.pop()
while (cur >= '0' and cur <= '9'):
tmp_s = cur + tmp_s
print(tmp_s)
if (len(stack) == 0):
last_op = 'num'
flag = True
break
cur = stack.pop()
last = int(tmp_s)
last_op = 'num'
else:
if (cur == '-'):
tmp -= last
else:
tmp += last
last_op = 'sym'
if (len(stack) == 0):
break
cur = stack.pop()
if (flag):
break
if (last_op != 'sym'):
tmp += last
return tmp