Postfix_to_infix
def post_to_infix(expression):
prec = {'+': 0, '-' : 0, '*' : 1, "/" : 1, '%' : 1, '^': 2}
stack = []
for x in expression:
if x == " ":
continue
if x in prec.keys():
#['+','-','*','/','%','^']:
if len(stack) < 2:
return "invalid";
op2 = stack.pop() # pop a wrapped list out
op1 = stack.pop()
if len(op2) > 1 and ((prec[op2[1]] < prec[x]) or (prec[op2[1]]== prec[x])):
op2 = "(%s)" % op2[0]
else:
op2 = op2[0]
if len(op1) > 1 and prec[op1[1]] < prec[x]:
op1 = "(%s)" % op1[0]
else:
op1 = op1[0]
stack.append(["%s%s%s" % (op1, x, op2), x])
else:
stack.append([x])
if len(stack) != 1:
return "invalid"
return stack.pop()[0]
s = post_to_infix("a b+cd--")
s = post_to_infix("")
print (s)Last updated
Was this helpful?