Python Program to Convert Infix to Postfix
Intermediate · Data structures
In infix notation the operator sits between its operands, as in A + B * C, while in postfix notation it comes after them, as in A B C * +. A computer can evaluate postfix from left to right with no brackets or precedence rules. This program converts infix to postfix with a stack that holds operators until it is their turn, which is how calculators and compilers do it.
Program
Infix: A + B * C Postfix: A B C * + Infix: (A + B) * C Postfix: A B + C * Infix: A * (B + C) / D Postfix: A B C + * D / Infix: A ^ B ^ C Postfix: A B C ^ ^ Infix: A + B * (C ^ D - E) ^ (F + G * H) - I Postfix: A B C D ^ E - F G H * + ^ * + I -
How it works
- Operands (letters or digits) go straight to the output, in the same order as in the infix expression.
- An opening bracket is pushed onto the stack, and a closing bracket pops operators to the output until the matching
(turns up. - Before an operator is pushed, every operator on the stack that must be done first is popped to the output: one with higher precedence, or one with the same precedence for left-to-right operators like
-and/. ^(power) is the exception, becauseA ^ B ^ CmeansA ^ (B ^ C), so an equal^stays on the stack and the result isA B C ^ ^.- At the end, the operators still on the stack are popped to the output; the program expects single-character operands and correctly matched brackets.
Other ways to write it
Showing the stack at every step
Symbol Stack Postfix A A * * A ( *( A B *( AB + *(+ AB C *(+ ABC ) * ABC+ / / ABC+* D / ABC+*D Postfix: ABC+*D/
This prints the table textbooks ask you to draw, with the symbol read, the stack after it and the postfix so far on each row; it leaves out ^, so >= works for every operator.
Evaluating a postfix expression
2 3 4 * + = 14 5 1 2 + 4 * + 3 - = 14
Postfix is easy for a computer: read left to right, push numbers, and when an operator arrives, pop two numbers, apply it and push the answer back, with no brackets or precedence needed.
Try it yourself
Add % to PRECEDENCE with the same precedence as *, and convert "A % B + C".
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises