Update 0150.逆波兰表达式求值.md

除法逻辑不完整,假如是5/2=2没问题,但如果是-5/2,会向下取整,就变成-3了,可以单独定义一个函数。

底下最先弹出的数字实际上是最后进入的数字,也就是运算符右边的操作数,而第二个弹出的数字是第一个进入的数字,即运算符左边的操作数。stack.append(operation(op2, op1))
This commit is contained in:
Meliodas417
2024-03-24 11:07:42 -05:00
committed by GitHub
parent 253bddcf37
commit 0e1cc6d277

View File

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