How to convert an expression from infix to postfix?

How to convert an expression from infix to postfix?

In this blog, we will explore how to convert an infix expression to a postfix expression and understand its usage.

What is an infix expression?

An infix expression is the common way we write mathematical expressions, where operators like + , -, * ,etc., are placed between operands. It is the format that we, as humans, are familiar with when solving expressions.

Example of an infix expression: a + b * (c ^ d - e) ^ (f + g * h) - i

What is a postfix expression?

A postfix expression places operators after their operands. Postfix notation is extremely useful in computing because computers follow strict rules for evaluating expressions, while humans can intuitively handle operator precedence. By using postfix notation, we simplify expressions so that computers can evaluate them directly without needing precedence rules.

The postfix form of the expression a + b is ab+.

Why is postfix useful?

When solving an expression, humans know to solve inside the parentheses first, followed by applying operator precedence. However, for a computer, we need a simpler form of expression where these rules are already handled, and that's what postfix notation offers.

How can we convert an infix expression to a postfix expression?

We use the stack data structure to store operators. The expression is scanned from left to right, processing one character at a time. Based on certain rules, we decide whether to push an operator onto the stack or append it to the result.

The process is as follows:

We traverse the infix expression from left to right considering each character let’s say x and our resultant answer is store in any data structure let’s say res.

  1. If the character is a left parenthesis (, push it onto the stack.

  2. If the character is an operand (alphanumeric), append it to the result (res).

  3. If the character is an operator, push it onto the stack if the stack is empty. If the stack is not empty, check the precedence of the current operator and the operator at the top of the stack:

    • If the current operator has greater precedence, push it onto the stack.

    • Otherwise, pop operators from the stack and append them to res until the stack's top operator has lower precedence or the stack is empty.

  4. If the character is a right parenthesis ), pop and append operators to res from the stack until a left parenthesis is encountered, then discard the left parenthesis.

  5. After iterating through the expression, pop all remaining operators from the stack and append them to the result.

Code for this problem in Python:

def InfixtoPostfix(exp):
        res = ''
        op_stack = []
        precedence = {'+':0, '-':0, '*':1, '/':1, '^':2, '(':3}

        for i in range(len(exp)):
            if exp[i].isalnum():
                res += exp[i]

            elif exp[i] == '(':
                op_stack.append('(')

            elif exp[i] == ')':
                while op_stack and op_stack[-1] != '(':
                    res += op_stack.pop()
                op_stack.pop()

            else:
                while op_stack and op_stack[-1] != '(' and precedence[exp[i]] <= precedence[op_stack[-1]]:
                        res += op_stack.pop()
                op_stack.append(exp[i])

        while op_stack:
            res += op_stack.pop()

        return res
  • Time Complexity: O(n) because we process each character of the expression once.

  • Space Complexity: O(n) due to storing the operators and the final result.

In this blog, we explored how to convert an infix expression to a postfix expression using a stack-based approach. Postfix notation simplifies the evaluation process for computers by eliminating the need for precedence rules. The Python code provided implements this conversion efficiently with a time complexity of O(n) and space complexity of O(n), making it suitable for expressions of any length.