根据 逆波兰表示法,求表达式的值
逆波兰表达式:是一种后缀表达式,所谓后缀就是指算符写在后面。
两个优点 1 去掉括号后无歧义 2 适合栈运算
本来想类似 20. 有效的括号 借助字典,例如{“+” : +},但是发现这种构不成字典
主要的困难是pop出stack中的元素进行运算
在python中有 eval(f'{b} {item} {a}') 这种操作,但是不知道
在使用if语句判断运算符时,除法会出现问题
python的 b / a 会向下取整, 比如 -1 / 132 = -1
题目要求是取整数部分,那么负数的时候,实际应该是向上取整, 解决方法: (b / float(a))
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
# 逆波兰表达式:是一种后缀表达式,所谓后缀就是指算符写在后面。
# 两个优点 1 去掉括号后无歧义 2 适合栈运算
stack = []
for i in tokens:
if tokens and i not in {"+", "-", "*", "/"}:
stack.append(i)
else:
x = stack.pop()
y = stack.pop()
if i == "+":
temp = int(y) + int(x)
elif i == "-":
temp = int(y) - int(x)
elif i == "*":
temp = int(y) * int(x)
# python的 b / a 会向下取整, 比如 -1 / 132 = -1。
#题目要求是取整数部分,那么负数的时候,实际应该是向上取整, 解决方法: (b / float(a))
elif i == "/":
temp = (int(y) / float(x))
stack.append(temp)
return int(stack.pop())
使用int(eval(f'{b} {item} {a}'))
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for item in tokens:
if tokens and item not in {"+", "-", "*", "/"}:
stack.append(item)
else:
a, b = stack.pop(), stack.pop()
stack.append(
int(eval(f'{b} {item} {a}')) # 第一个出来的在运算符后面
)
return int(stack.pop())