|
| 1 | +# function to convert infix to postfix using array as stack |
| 2 | +def infix_to_postfix(infix_expression): |
| 3 | + """ |
| 4 | + Function to change infix expression to postfix one |
| 5 | + Params: |
| 6 | + infix_expression: Infix Expression provided by user |
| 7 | + Returns: |
| 8 | + postfix_expression: Postfix Expression convertef from Infix one |
| 9 | + """ |
| 10 | + |
| 11 | + # initially empty stack |
| 12 | + stack = [] |
| 13 | + # initially empty postfix_expression |
| 14 | + postfix_expression = "" |
| 15 | + for char in infix_expression: |
| 16 | + # if an operand then put it directly in postfix expression |
| 17 | + if char not in operators: |
| 18 | + postfix_expression += char |
| 19 | + # else if operators should be put in stack |
| 20 | + elif char == "(": |
| 21 | + """append function to push |
| 22 | + elements in the stack""" |
| 23 | + stack.append("(") |
| 24 | + elif char == ")": |
| 25 | + while stack and stack[-1] != "(": |
| 26 | + postfix_expression += stack.pop() |
| 27 | + """ pop function to pop |
| 28 | + elements from stack in LIFO order """ |
| 29 | + stack.pop() |
| 30 | + else: |
| 31 | + """if priority of char in infix_expression is less than or equal to |
| 32 | + char at stack[-1] pop out and put in postfix_expression""" |
| 33 | + while ( |
| 34 | + stack and stack[-1] != "(" and priorities[char] <= priorities[stack[-1]] |
| 35 | + ): |
| 36 | + postfix_expression += stack.pop() |
| 37 | + stack.append(char) |
| 38 | + while stack: |
| 39 | + postfix_expression += stack.pop() |
| 40 | + return postfix_expression |
| 41 | + |
| 42 | + |
| 43 | +# Set of operators |
| 44 | +operators = set(["+", "-", "*", "/", "(", ")", "^"]) |
| 45 | + |
| 46 | +# dictionary having priorities |
| 47 | +priorities = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3} |
| 48 | + |
| 49 | +print("Input") |
| 50 | +infix_expression = input("Enter infix expression\n") |
| 51 | +print("Output") |
| 52 | + |
| 53 | +# Displaying the Output |
| 54 | +print("Postfix expression: ", infix_to_postfix(infix_expression)) |
0 commit comments