mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #2862 from yyccPhil/leetcode-150
fix: 150题更正Python解法中使用eval()的方法
This commit is contained in:
@ -188,34 +188,21 @@ class Solution(object):
|
|||||||
return stack.pop()
|
return stack.pop()
|
||||||
```
|
```
|
||||||
|
|
||||||
另一种可行,但因为使用eval相对较慢的方法:
|
另一种可行,但因为使用eval()相对较慢的方法:
|
||||||
```python
|
```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):
|
class Solution(object):
|
||||||
op_map = {'+': add, '-': sub, '*': mul, '/': div}
|
def evalRPN(self, tokens: List[str]) -> int:
|
||||||
|
|
||||||
def evalRPN(self, tokens):
|
|
||||||
"""
|
|
||||||
:type tokens: List[str]
|
|
||||||
:rtype: int
|
|
||||||
"""
|
|
||||||
stack = []
|
stack = []
|
||||||
for token in tokens:
|
for token in tokens:
|
||||||
if token in self.op_map:
|
# 判断是否为数字,因为isdigit()不识别负数,故需要排除第一位的符号
|
||||||
op1 = stack.pop()
|
if token.isdigit() or (len(token)>1 and token[1].isdigit()):
|
||||||
op2 = stack.pop()
|
stack.append(token)
|
||||||
operation = self.op_map[token]
|
|
||||||
stack.append(operation(op2, op1))
|
|
||||||
else:
|
else:
|
||||||
stack.append(int(token))
|
op2 = stack.pop()
|
||||||
return stack.pop()
|
op1 = stack.pop()
|
||||||
|
# 由题意"The division always truncates toward zero",所以使用int()可以天然取整
|
||||||
|
stack.append(str(int(eval(op1 + token + op2))))
|
||||||
|
return int(stack.pop())
|
||||||
```
|
```
|
||||||
|
|
||||||
### Go:
|
### Go:
|
||||||
|
Reference in New Issue
Block a user