我直接震惊、、、怪不得一开始一直不过 卡在了这里 我淦
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
'''
思路:栈实现,遇着数字入栈,遇着运算符出栈
'''
stack = []
for i in tokens:
if i not in ['+','-','*','/']: # 判断该字符是否为字符串
stack.append(int(i))
else:
a,b = stack.pop(),stack.pop() # 根据题意,stack里面必定至少有俩元素
if i == '+':
stack.append(b+a)
elif i == '-':
stack.append(b-a)
elif i == '/':
stack.append(int(b/a))
else:
stack.append(b*a)
return stack.pop()
看了一下答案,这个语句写的确实六六
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()) # 如果一开始只有一个数,那么会是字符串形式的