我写了波兰符号算法。但是如果操作符之间有相同的操作数,它就不能正常工作。如果我们使用当前列表 ['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()