Skip to content

Commit 74f1810

Browse files
Merge pull request #2492 from Meliodas417/master
Update 0150.逆波兰表达式求值.md
2 parents 7c5e1c5 + 0e1cc6d commit 74f1810

File tree

1 file changed

+29
-12
lines changed

1 file changed

+29
-12
lines changed

problems/0150.逆波兰表达式求值.md

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,12 @@ class Solution {
169169
```python
170170
from operator import add, sub, mul
171171

172-
class Solution:
173-
op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}
172+
def div(x, y):
173+
# 使用整数除法的向零取整方式
174+
return int(x / y) if x * y > 0 else -(abs(x) // abs(y))
175+
176+
class Solution(object):
177+
op_map = {'+': add, '-': sub, '*': mul, '/': div}
174178

175179
def evalRPN(self, tokens: List[str]) -> int:
176180
stack = []
@@ -186,18 +190,31 @@ class Solution:
186190

187191
另一种可行,但因为使用eval相对较慢的方法:
188192
```python
189-
class Solution:
190-
def evalRPN(self, tokens: List[str]) -> int:
193+
from operator import add, sub, mul
194+
195+
def div(x, y):
196+
# 使用整数除法的向零取整方式
197+
return int(x / y) if x * y > 0 else -(abs(x) // abs(y))
198+
199+
class Solution(object):
200+
op_map = {'+': add, '-': sub, '*': mul, '/': div}
201+
202+
def evalRPN(self, tokens):
203+
"""
204+
:type tokens: List[str]
205+
:rtype: int
206+
"""
191207
stack = []
192-
for item in tokens:
193-
if item not in {"+", "-", "*", "/"}:
194-
stack.append(item)
208+
for token in tokens:
209+
if token in self.op_map:
210+
op1 = stack.pop()
211+
op2 = stack.pop()
212+
operation = self.op_map[token]
213+
stack.append(operation(op2, op1))
195214
else:
196-
first_num, second_num = stack.pop(), stack.pop()
197-
stack.append(
198-
int(eval(f'{second_num} {item} {first_num}')) # 第一个出来的在运算符后面
199-
)
200-
return int(stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的
215+
stack.append(int(token))
216+
return stack.pop()
217+
201218

202219
```
203220

0 commit comments

Comments
 (0)