|
| 1 | +""" |
| 2 | +https://math.oxford.emory.edu/site/cs171/postfixExpressions/ |
| 3 | +https://en.wikipedia.org/wiki/Shunting_yard_algorithm |
| 4 | +""" |
| 5 | + |
| 6 | + |
| 7 | +def postfix_to_infix(postfix_expression: str) -> str: |
| 8 | + """ |
| 9 | + Returns the infix expression for the given postfix expression as an argument |
| 10 | + >>> postfix_to_infix("") |
| 11 | + Traceback (most recent call last): |
| 12 | + ... |
| 13 | + ValueError: Invalid postfix expression. |
| 14 | + >>> postfix_to_infix("123+*4+") |
| 15 | + '((1*(2+3))+4)' |
| 16 | + >>> postfix_to_infix("abc*+de*f+g*+") |
| 17 | + '((a+(b*c))+(((d*e)+f)*g))' |
| 18 | + >>> postfix_to_infix("xy^5z*/2+") |
| 19 | + '(((x^y)/(5*z))+2)' |
| 20 | + >>> postfix_to_infix("232^^") |
| 21 | + '(2^(3^2))' |
| 22 | + >>> postfix_to_infix("32+") |
| 23 | + '(3+2)' |
| 24 | + """ |
| 25 | + |
| 26 | + # Check for invalid input. |
| 27 | + if postfix_expression is None or postfix_expression == "": |
| 28 | + raise ValueError("Invalid postfix expression.") |
| 29 | + |
| 30 | + # Create a stack to store the operands and operators. |
| 31 | + stack = [] |
| 32 | + |
| 33 | + # Iterate over the postfix expression. |
| 34 | + for item in postfix_expression: |
| 35 | + # If the item is an operand, push it onto the stack. |
| 36 | + if item not in ["+", "-", "*", "/", "^"]: |
| 37 | + stack.append(item) |
| 38 | + else: |
| 39 | + # If the item is an operator, pop the top two operands from the stack |
| 40 | + # and concatenate the operator between them. |
| 41 | + operand_2 = stack.pop() |
| 42 | + operand_1 = stack.pop() |
| 43 | + infix_expression = "(" + operand_1 + item + operand_2 + ")" |
| 44 | + |
| 45 | + # Push the resulting infix expression onto the stack. |
| 46 | + stack.append(infix_expression) |
| 47 | + |
| 48 | + # The top element of the stack is the final infix expression. |
| 49 | + return stack.pop() |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + from doctest import testmod |
| 54 | + |
| 55 | + testmod() |
| 56 | + # Enter the posfix expression with no whitespaces. |
| 57 | + postfix_expression = "512+4*+3-" |
| 58 | + |
| 59 | + try: |
| 60 | + infix_expression = postfix_to_infix(postfix_expression) |
| 61 | + print("Infix expression: " + infix_expression) |
| 62 | + except ValueError as e: |
| 63 | + print(e) |
0 commit comments