I've written polish notation algorithm. But it doesn`t work properly, if there are the same operands between operator. If we run this code with current list ['a', '+', 'a', '*', 'b'], it will work properly, but if we change(b) on (a) it won't. The result in the first case is (a, a, b, *, +) and in the second (a, a, +, a, *). Why does it happen?
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()