Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0fa443c

Browse files
fix: 150题更正Python解法中使用eval()的方法
此处原本提供的两个python解法是一样的,并无区别;更正为实际上真正使用eval()的方法。
1 parent a8382d9 commit 0fa443c

File tree

1 file changed

+9
-23
lines changed

1 file changed

+9
-23
lines changed

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

Lines changed: 9 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -188,34 +188,20 @@ class Solution(object):
188188
return stack.pop()
189189
```
190190

191-
另一种可行,但因为使用eval相对较慢的方法:
191+
另一种可行,但因为使用eval()相对较慢的方法:
192192
```python
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-
199193
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-
"""
194+
def evalRPN(self, tokens: List[str]) -> int:
207195
stack = []
208196
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))
197+
# 判断是否为数字,因为isdigit()不识别负数,故需要排除第一位的符号
198+
if token.isdigit() or (len(token)>1 and token[1].isdigit()):
199+
stack.append(token)
214200
else:
215-
stack.append(int(token))
216-
return stack.pop()
217-
218-
201+
op2 =stack.pop()
202+
op1 = stack.pop()
203+
stack.append(str(int(eval(op1 + token + op2))))
204+
returnint(stack.pop())
219205
```
220206

221207
### Go:

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /