Merge pull request #2492 from Meliodas417/master

Update 0150.逆波兰表达式求值.md
This commit is contained in:
程序员Carl
2024-04-26 11:49:51 +08:00
committed by GitHub

View File

@ -169,8 +169,12 @@ class Solution {
```python
from operator import add, sub, mul
class Solution:
op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}
def div(x, y):
# 使用整数除法的向零取整方式
return int(x / y) if x * y > 0 else -(abs(x) // abs(y))
class Solution(object):
op_map = {'+': add, '-': sub, '*': mul, '/': div}
def evalRPN(self, tokens: List[str]) -> int:
stack = []
@ -186,18 +190,31 @@ class Solution:
另一种可行但因为使用eval相对较慢的方法:
```python
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
from operator import add, sub, mul
def div(x, y):
# 使用整数除法的向零取整方式
return int(x / y) if x * y > 0 else -(abs(x) // abs(y))
class Solution(object):
op_map = {'+': add, '-': sub, '*': mul, '/': div}
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for item in tokens:
if item not in {"+", "-", "*", "/"}:
stack.append(item)
for token in tokens:
if token in self.op_map:
op1 = stack.pop()
op2 = stack.pop()
operation = self.op_map[token]
stack.append(operation(op2, op1))
else:
first_num, second_num = stack.pop(), stack.pop()
stack.append(
int(eval(f'{second_num} {item} {first_num}')) # 第一个出来的在运算符后面
)
return int(stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的
stack.append(int(token))
return stack.pop()
```