我写了波兰语符号算法。但是如果运算符之间有相同的操作数,它就不能正常工作。如果我们用当前列表 ['a', '+', 'a', '*', 'b'] 运行这段代码,它会正常工作,但如果我们在 (a) 上更改 (b),它就不会. 第一种情况的结果是 (a, a, b, *, +),第二种情况的结果是 (a, a, +, a, *)。为什么会这样?
operators = ["+", "-"]
operators1 = ["*", "/"]
operators2 = ["^"]
operators3 = ["(", ")"]
all_operators = ["+", "-", "*", "/", "^"]
def get_priority(operator):
if operator in operators:
priority = 1
if operator in operators1:
priority = 2
if operator in operators2:
priority = 3
if operator in operators3:
priority = 4
return priority
def notation():
exit = []
stack = []
list = ['a', '+', 'a', '*', 'b']
for i in list:
if i not in all_operators:
exit.append(i)
else:
stack.append(i)
while len(stack) > 1 and get_priority(stack[-2]) >= get_priority(stack[-1]):
exit.append(stack.pop(-2))
if i is list[-1]:
while len(stack) > 0:
exit.append(stack.pop())
print(exit)
notation()
慕少森
相关分类