Leetcode Link: 150. 逆波兰表达式求值 - 力扣(LeetCode)
题目
根据 逆波兰表示法,求表达式的值。
有效的算符包括 +、-、*、/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
注意 两个整数之间的除法只保留整数部分。
可以保证给定的逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

解法一
思路: 遇到运算法则就弹出两个做运算,并把结果压入 否则就压入
题解:
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = collections.deque()
op = ["+", "-", "*", "/"]
if len(tokens)==1:
return int(tokens[0])
for val in tokens:
if val not in op:
stack.append(val)
else:
num2 = int(stack.pop())
num1 = int(stack.pop())
if val == "+":
tmp_res = num1 + num2
elif val == "-":
tmp_res = num1 - num2
elif val == "*":
tmp_res = num1 * num2
elif val == "/":
tmp_res = int(num1 / num2)
stack.append(tmp_res)
return tmp_res