Skip to content

Commit 1b40e66

Browse files
authored
Merge pull request #490 from pushpit-J19/infix_to_postfix
Added python file for infix to postfix
2 parents 5c93bd7 + 6c4ebfe commit 1b40e66

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""
2+
Algorithm
3+
1. Scan the infix expression from left to right.
4+
2. If the scanned character is an ‘(‘, push it to the stack.
5+
3. else If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, discard both '(' and ')'
6+
4. else If the scanned character is an operand, output it.
7+
5. Else if it is an operand,
8+
1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack or the stack is empty or the stack contains a ‘(‘ , push it onto the stack.
9+
2 Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator until the stack is not empty or '(' is not encountered. After doing that Push the scanned operator to the stack.
10+
6. Repeat steps 2-6 until infix expression is scanned.
11+
7. Empty the stack into the output
12+
8. Print the output
13+
"""
14+
15+
operators = {'+':1,'-':1,'*':3,'/':3,'^':5}
16+
17+
# Tells if a given list is empty or not
18+
def isEmpty (l):
19+
return not l
20+
21+
22+
def infix_to_postfix (infix):
23+
"""Converts infix expression to postfix
24+
takes argument : infix expression string
25+
returns : equivalent postfix expressiion string"""
26+
post = ""
27+
stack = []
28+
top = -1
29+
for c in infix:
30+
31+
if c == "(":
32+
stack.append(c)
33+
elif c == ")":
34+
while not isEmpty(stack):
35+
if stack[top] == "(":
36+
stack.pop()
37+
break
38+
else :
39+
post += stack.pop()
40+
41+
elif c.isalpha():
42+
post += c
43+
elif c in operators:
44+
if isEmpty(stack) or stack[top] == "(" or operators[c] > operators[stack[top]]:
45+
stack.append(c)
46+
47+
else: # operators
48+
while not isEmpty(stack) :
49+
if stack[top] == "(" :
50+
break
51+
52+
if operators[stack[top]] >= operators[c] :
53+
post += stack.pop()
54+
else:
55+
stack.append(c)
56+
if isEmpty(stack) or stack[top]=="(":
57+
stack.append(c)
58+
print(c, stack, post)
59+
60+
while not isEmpty(stack):
61+
post += stack.pop()
62+
63+
print(stack)
64+
return post
65+
66+
67+
# DRIVER CODE
68+
if __name__ == "__main__":
69+
70+
infix_exp = "a+b*(c^d-e)^(f+g*h)-i"
71+
postfix_exp = infix_to_postfix(infix_exp)
72+
73+
print("\nInfix Expression : ", infix_exp)
74+
print("\nEquivalent Postfix expression : ", postfix_exp)
75+
76+
# Expected output = abcd^e-fgh*+^*+i-
77+
# Actual output = abcd^e-fgh*+^*+i-

0 commit comments

Comments
 (0)