Solution Review: Prefix to Postfix Conversion
The solution to the 'Prefix to Postfix Conversion' challenge.
We'll cover the following...
Algorithm
Before moving onto the code, let’s see the following steps to solve the problem:
- Scan the expression from right to left. For every symbol, check whether it’s an operator or operand.
- If it is an operand, push it into the stack.
- If it is an operator, pop from the stack two times.
- Concatenate the popped items and the operator.
- Push the concatenated result into the stack.
- When traversing through the expression is complete, the stack will hold one element only, i.e., the final result (the postfix expression).
Press + to interact
from collections import dequedef postfix(prefix):stack = deque()prefix = ''.join((reversed(prefix))) #Reversing the expressionfor symbol in prefix:if symbol != '+' and symbol != '-' and symbol != '*' and symbol != '/':stack.append(symbol) # Push if an operandelse:# If an operator, then pop two operands from stackoperand1 = stack.pop()operand2 = stack.pop()# Concatenate operands and operator and again push it in stackstack.append(operand1+operand2+symbol)return(stack.pop()) # Poping the resultprint(postfix('*-A/BC+/AKL'))
...