我直接震惊、、、怪不得一开始一直不过 卡在了这里 我淦
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()
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())
|