File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Author: OMKAR PATHAK
2
+
3
+ import Stack
4
+
5
+ def isOperand (char ):
6
+ return (ord (char ) >= ord ('a' ) and ord (char ) <= ord ('z' )) or (ord (char ) >= ord ('A' ) and ord (char ) <= ord ('Z' ))
7
+
8
+ def precedence (char ):
9
+ if char == '+' or char == '-' :
10
+ return 1
11
+ elif char == '*' or char == '/' :
12
+ return 2
13
+ elif char == '^' :
14
+ return 3
15
+ else :
16
+ return - 1
17
+
18
+ def infixToPostfix (myExp , myStack ):
19
+ postFix = []
20
+ for i in range (len (myExp )):
21
+ if (isOperand (myExp [i ])):
22
+ postFix .append (myExp [i ])
23
+ elif (myExp [i ] == '(' ):
24
+ myStack .push (myExp [i ])
25
+ elif (myExp [i ] == ')' ):
26
+ topOperator = myStack .pop ()
27
+ while (not myStack .isEmpty () and topOperator != '(' ):
28
+ postFix .append (topOperator )
29
+ topOperator = myStack .pop ()
30
+ else :
31
+ while (not myStack .isEmpty ()) and (precedence (myExp [i ]) <= precedence (myStack .peek ())):
32
+ postFix .append (myStack .pop ())
33
+ myStack .push (myExp [i ])
34
+
35
+ while (not myStack .isEmpty ()):
36
+ postFix .append (myStack .pop ())
37
+ return ' ' .join (postFix )
38
+
39
+ if __name__ == '__main__' :
40
+ myExp = 'a+b*(c^d-e)^(f+g*h)-i'
41
+ myExp = [i for i in myExp ]
42
+ print ('Infix:' ,' ' .join (myExp ))
43
+ myStack = Stack .Stack (len (myExp ))
44
+ print ('Postfix:' ,infixToPostfix (myExp , myStack ))
45
+
46
+ # OUTPUT:
47
+ # Infix: a + b * ( c ^ d - e ) ^ ( f + g * h ) - i
48
+ # Postfix: a b c d ^ e - f g h * + ^ * + i -
You can’t perform that action at this time.
0 commit comments