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

[pull] master from youngyangyang04:master #516

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 6 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Dec 27, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 10 additions & 23 deletions problems/0150.逆波兰表达式求值.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -188,34 +188,21 @@ 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()
# 由题意"The division always truncates toward zero",所以使用int()可以天然取整
stack.append(str(int(eval(op1 + token + op2))))
return int(stack.pop())
```

### Go:
Expand Down

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