fix: 150题更正Python解法中使用eval()的方法

此处原本提供的两个python解法是一样的,并无区别;更正为实际上真正使用eval()的方法。
This commit is contained in:
Yuan Yuan
2024-12-26 14:03:38 -06:00
committed by GitHub
parent a8382d91c3
commit 0fa443ce1a

View File

@ -188,34 +188,20 @@ class Solution(object):
return stack.pop()
```
另一种可行但因为使用eval相对较慢的方法:
另一种可行但因为使用eval()相对较慢的方法:
```python
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
"""
def evalRPN(self, tokens: List[str]) -> int:
stack = []
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))
# 判断是否为数字因为isdigit()不识别负数,故需要排除第一位的符号
if token.isdigit() or (len(token)>1 and token[1].isdigit()):
stack.append(token)
else:
stack.append(int(token))
return stack.pop()
op2 = stack.pop()
op1 = stack.pop()
stack.append(str(int(eval(op1 + token + op2))))
return int(stack.pop())
```
### Go: