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.

conversion 2

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, also known as Polish notation, are challenging to comprehend for humans due to their unconventional structure. Converting them to infix notation, which is more intuitive and widely used, can significantly improve the readability of expressions and simplify the evaluation process.

For example, the infix expression (5 + 3) is represented in prefix notation as + 5 3. This notation eliminates the need for parentheses to specify the order of operations, making it particularly valuable for computer algorithms and mathematical parsing.

prefix to infix conversion

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.

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)

Conclusion

In conclusion, 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.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Question 1.

Can I convert infix expressions to prefix using a similar process?

Yes, you can perform the reverse process by converting infix expressions to prefix using a similar set of rules.

Question 2.

What is the difference between prefix and infix notation?

Prefix notation places operators before operands, while infix notation puts operators between operands, making it the more common and human-friendly format.

Question 3.

 Why do we need to convert prefix to infix expressions?

Converting to infix improves code readability and makes mathematical expressions more understandable for humans.

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

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription