-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy path227_basic_calculator_ii.py
More file actions
130 lines (105 loc) · 3.13 KB
/
227_basic_calculator_ii.py
File metadata and controls
130 lines (105 loc) · 3.13 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
s = self.to_rpn(s, {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
})
if not s:
return 0
return self.eval_rpn(s, {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a // b,
})
def to_rpn(self, s, P):
stack, res = [], []
for i in range(len(s)):
char = s[i]
if i > 0 and s[i - 1].isdigit() and char.isdigit():
res[-1] += char
elif char.isdigit():
res.append(char)
elif char in P:
while stack and stack[-1] in P and P[char] <= P[stack[-1]]:
res.append(stack.pop())
stack.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
res.append(stack.pop())
stack.pop()
while stack:
res.append(stack.pop())
return res
def eval_rpn(self, s, OP):
stack = []
for char in s:
if char.isdigit():
stack.append(int(char))
elif char in OP:
b = stack.pop()
a = stack.pop()
stack.append(OP[char](a, b))
return stack[0]
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
s = self.to_rpn(s)
if not s:
return 0
return self.eval_rpn(s)
def to_rpn(self, s):
stack, res = [], []
for i in range(len(s)):
char = s[i]
if i > 0 and s[i - 1].isdigit() and char.isdigit():
res[-1] += char
elif char.isdigit():
res.append(char)
elif char in '+-*/':
while stack and stack[-1] in '+-*/':
if char in '*/' and stack[-1] in '+-':
break
res.append(stack.pop())
stack.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
res.append(stack.pop())
stack.pop()
while stack:
res.append(stack.pop())
return res
def eval_rpn(self, s):
stack = []
for char in s:
if char.isdigit():
stack.append(int(char))
elif char in '+-*/':
b = stack.pop()
a = stack.pop()
if char == '+':
stack.append(a + b)
elif char == '-':
stack.append(a - b)
elif char == '*':
stack.append(a * b)
elif char == '/':
stack.append(a // b)
return stack[0]