Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1849 from myfix16/master
Browse files Browse the repository at this point in the history
0150.逆波兰表达式求值 添加更快速的python解
  • Loading branch information
youngyangyang04 authored Jan 13, 2023
2 parents cb5bf39 + abedcbb commit 6d74c17
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions problems/0150.逆波兰表达式求值.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,25 @@ class Solution {

python3

```python
from operator import add, sub, mul

class Solution:
op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}

def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token not in {'+', '-', '*', '/'}:
stack.append(int(token))
else:
op2 = stack.pop()
op1 = stack.pop()
stack.append(self.op_map[token](op1, op2)) # 第一个出来的在运算符后面
return stack.pop()
```

另一种可行,但因为使用eval相对较慢的方法:
```python
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
Expand Down

0 comments on commit 6d74c17

Please sign in to comment.