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