Prefix to Infix Conversion in Python
Prefix to Infix Conversion in Python
In the world of programming, efficiency and readability are of utmost importance. Converting expressions from one format to another can significantly impact code clarity and performance. One such conversion that developers often encounter is transforming prefix to infix conversion in Python.
In this page, we will delve into the intricacies of prefix to infix conversion, exploring the process step by step.

Understanding Prefix to Infix Conversion
Prefix to Infix conversion is a crucial concept in computer science and mathematics, particularly in the realm of expression evaluation. This process involves converting expressions from prefix notation to infix notation. In simpler terms, it’s all about changing the order of operands and operators to make expressions more human-readable and understandable.
Why Prefix to Infix Conversion Matters
- Prefix expressions (Polish notation) are harder for humans to understand due to their structure.
- Converting them to infix form improves readability and ease of evaluation.
- Infix notation is more familiar and widely used in mathematics and programming.
- Example: Infix (5 + 3) is written as + 5 3 in prefix.
- Prefix eliminates the need for parentheses, aiding in algorithmic parsing.

The Algorithm for Prefix to Infix Conversion
- To perform Prefix to Infix conversion, you need to follow a systematic algorithm. Here’s a step-by-step guide:
Step 1: Start from the End of the Prefix Expression
Begin by scanning the prefix expression from right to left.
Step 2: Operand or Operator?
For each element in the expression, check whether it’s an operand or an operator.
Step 3: Operand Handling
If you encounter an operand (a variable or a constant), push it onto a stack.
Step 4: Operator Handling
- If you encounter an operator (+, -, *, /, etc.), pop two operands from the stack.
- Place the operator between the two operands, creating a subexpression.
- Push this subexpression back onto the stack.
Step 5: Repeat
Continue this process until you’ve processed the entire prefix expression.
Step 6: Final Expression
At the end, the stack should contain the fully converted infix expression.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Implementation of Prefix to Infix Conversion in Python
def prefix_to_infix(expression): stack = [] operators = set(['+', '-', '*', '/']) for char in expression[::-1]: if char not in operators: stack.append(char) else: operand1 = stack.pop() operand2 = stack.pop() infix_expression = f'({operand1} {char} {operand2})' stack.append(infix_expression) return stack[0]
Prefix to Infix Conversion Example Usage
Prefix Expression
* + 2 3 5
Conversion
- Start with the rightmost element ‘5’, push it onto the stack.
- Move to ‘3’, push it onto the stack.
- Encounter ‘+’, pop ‘3’ and ‘5’, form ‘3 + 5’, and push it back onto the stack.
- Finally, encounter ‘*’, pop ‘2’ and ‘(3 + 5)’, form ‘2 * (3 + 5)’, and push the final result onto the stack.
- The result will be:
The result will be :
2 * (3 + 5)
Prefix to Infix Conversion : Problem Statement
Convert a given arithmetic expression in prefix notation to its equivalent infix notation. The input expression is provided as a string, and the output should also be a string representing the infix notation of the expression. The expression may contain operators (+, -, *, /), operands (single-digit integers), and parentheses for grouping.
Input:
Prefix Expression: + * 5 4 - 7 2
Implementation Python Code :
def is_operator(char): return char in ['+', '-', '*', '/'] def prefix_to_infix(expression): stack = [] tokens = expression.split() for token in reversed(tokens): if token.isdigit(): stack.append(token) elif is_operator(token): operand1 = stack.pop() operand2 = stack.pop() infix_expression = f'({operand1} {token} {operand2})' stack.append(infix_expression) if len(stack) == 1: return stack[0] else: raise ValueError("Invalid prefix expression") # Example usage: prefix_expression = "+ * 5 4 - 7 2" infix_expression = prefix_to_infix(prefix_expression) print("Prefix Expression:", prefix_expression) print("Infix Expression:", infix_expression)
Output :
Infix Expression: (5 * 4) + (7 - 2)
Time and Space Complexity:
- Time Complexity: O(n) – Each token in the prefix expression is processed exactly once.
- Space Complexity: O(n) – A stack is used to store intermediate expressions, which in the worst case may hold up to n elements.
Takeaway:
understanding and implementing prefix to infix conversion in Python can enhance your coding skills and contribute to more readable and maintainable code. Converting expressions from one notation to another is a valuable skill that every programmer should possess.
FAQs
Prefix to infix conversion transforms expressions from Polish notation to standard mathematical form. It improves human readability by reinstating operators between operands with correct parentheses.
The algorithm uses a stack and processes the expression from right to left. When an operator is found, it pops two operands from the stack, combines them, and pushes the result back.
Yes, by splitting the prefix string with spaces, multi-digit numbers or variable names can be handled. Each token is checked whether it’s an operator or operand accordingly.
It requires valid input format and balanced operators/operands. Incorrect expressions can lead to stack underflow or malformed infix results during conversion.
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment