Javatpoint Logo
Javatpoint Logo

Postfix to Infix Conversion in Python

Infix expression: Infix expressions contain the operator in between the two operands. The operands can themselves contain operators. Though with respect to the middle operator, the expression will be an infix expression.

Infix expressions are of the form

Example: (X + Y) * (X1 + Y1)

Postfix expression: Postfix expressions contain the operator at the end of the two operands. The operands can themselves contain operators. Though with respect to the operator, at the end, the expression will be a postfix expression.

Postfix expressions are of the form

Example: XY - X1Y1+* (Infix: (X - Y) * (X1 + Y1))

Postfix expressions are also known as reverse Polish expressions. Computers are designed to compute the expressions most often in postfix or sometimes in prefixes. However, it is difficult for us to understand and compute a postfix expression.

Postfix Expressions Are Complex

Postfix expressions can be very complicated, with multiple parentheses and operators present in a certain order. We are trained to solve infix expressions. Therefore, we need to convert a prefix expression to an infix expression.

Here are some sample inputs and outputs for a better understanding of the problem at hand.

Examples:

Input: xyz++

Output: (x + (y + z))

Input: xy*z+

Output: ((x*y)+z)

Algorithm

  1. We will create a while loop, and the condition will be that the loop will work until there are symbols in the string.
  2. The interpreter will read the symbols one by one
  3. If the symbol is an operand, then it will be pushed onto the stack.
  4. Else, if the symbol is an operator, we will pop two items from the stack. We will insert the operator with the values as its arguments and construct a string of these. Then we will push this string back onto the stack.
  5. If the stack has only one value, then that value is the required infix string.

Here is the implementation of this algorithm in Python

Code

Output:

The infix expression is: 
((x*y)+z) 

Time Complexity: This algorithm has O(n) time complexity, where n is the length of the given prefix string.

Auxiliary Space: Since we are string the symbols of the string in the stack, this program takes O(n) memory space.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA