mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
更新 0150.逆波兰表达式求值.md python代码
用format string提升效率,增加可读性,避免使用索引访问,直接使用切片。
This commit is contained in:
@ -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 {"+", "-", "*", "/"}:
|
||||||
|
stack.append(item)
|
||||||
else:
|
else:
|
||||||
tmp1 = stack.pop()
|
first_num, second_num = stack.pop(), stack.pop()
|
||||||
tmp2 = stack.pop()
|
stack.append(
|
||||||
res = eval(tmp2+tokens[i]+tmp1)
|
int(eval(f'{second_num} {item} {first_num}')) # 第一个出来的在运算符后面
|
||||||
stack.append(str(int(res)))
|
)
|
||||||
return stack[-1]
|
return int(stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user