更新 0150.逆波兰表达式求值.md python代码

用format string提升效率,增加可读性,避免使用索引访问,直接使用切片。
This commit is contained in:
Eyjan_Huang
2021-08-20 17:14:16 +08:00
committed by GitHub
parent ca576c5bd0
commit 02fcd2c4a8

View File

@ -223,17 +223,19 @@ var evalRPN = function(tokens) {
python3
```python
def evalRPN(tokens) -> int:
stack = list()
for i in range(len(tokens)):
if tokens[i] not in ["+", "-", "*", "/"]:
stack.append(tokens[i])
else:
tmp1 = stack.pop()
tmp2 = stack.pop()
res = eval(tmp2+tokens[i]+tmp1)
stack.append(str(int(res)))
return stack[-1]
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for item in tokens:
if item not in {"+", "-", "*", "/"}:
stack.append(item)
else:
first_num, second_num = stack.pop(), stack.pop()
stack.append(
int(eval(f'{second_num} {item} {first_num}')) # 第一个出来的在运算符后面
)
return int(stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的
```