Convert an expression written in postfix notation to infix notation

A postfix expression is one where each operator comes after it's operands, while in an infix expression the operator is in between the operands. For example, the postfix expression ab+c/ is equivalent to (a+b)/c in infix notation

Your code should take a string of arbitrary length, convert it to postfix and return the equivalent infix expression

  • Your Solution should detect invalid expressions and output "invalid" in that case.
  • The only valid operators are +, -, *,/ and ^ (exponentiation operator)
  • You can assume that all operands are single characters.
  • Operands and operators may or may not be separated by spaces.
  • Your solution must enclose expression in the minimal set of parentheses to appropriately preserve the order of operations.
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)

results matching ""

    No results matching ""