|
| 1 | +""" |
| 2 | +Output: |
| 3 | +
|
| 4 | +Enter an Infix Equation = a + b ^c |
| 5 | + Symbol | Stack | Postfix |
| 6 | +---------------------------- |
| 7 | + a | | a |
| 8 | + + | + | a |
| 9 | + b | + | ab |
| 10 | + ^ | +^ | ab |
| 11 | + c | +^ | abc |
| 12 | + | + | abc^ |
| 13 | + | | abc^+ |
| 14 | +
|
| 15 | + a+b^c -> abc^+ |
| 16 | +""" |
| 17 | + |
| 18 | +def infix_2_postfix(Infix): |
| 19 | + Stack = [] |
| 20 | + Postfix = [] |
| 21 | + priority = {'^':3, '*':2, '/':2, '%':2, '+':1, '-':1} # Priority of each operator |
| 22 | + print_width = len(Infix) if(len(Infix)>7) else 7 |
| 23 | + |
| 24 | + # Print table header for output |
| 25 | + print('Symbol'.center(8), 'Stack'.center(print_width), 'Postfix'.center(print_width), sep = " | ") |
| 26 | + print('-'*(print_width*3+7)) |
| 27 | + |
| 28 | + for x in Infix: |
| 29 | + if(x.isalpha() or x.isdigit()): Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix |
| 30 | + elif(x == '('): Stack.append(x) # if x is "(" push to Stack |
| 31 | + elif(x == ')'): # if x is ")" pop stack until "(" is encountered |
| 32 | + while(Stack[-1] != '('): |
| 33 | + Postfix.append( Stack.pop() ) #Pop stack & add the content to Postfix |
| 34 | + Stack.pop() |
| 35 | + else: |
| 36 | + if(len(Stack)==0): Stack.append(x) #If stack is empty, push x to stack |
| 37 | + else: |
| 38 | + while( len(Stack) > 0 and priority[x] <= priority[Stack[-1]]): # while priority of x is not greater than priority of element in the stack |
| 39 | + Postfix.append( Stack.pop() ) # pop stack & add to Postfix |
| 40 | + Stack.append(x) # push x to stack |
| 41 | + |
| 42 | + print(x.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format |
| 43 | + |
| 44 | + while(len(Stack) > 0): # while stack is not empty |
| 45 | + Postfix.append( Stack.pop() ) # pop stack & add to Postfix |
| 46 | + print(' '.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format |
| 47 | + |
| 48 | + return "".join(Postfix) # return Postfix as str |
| 49 | + |
| 50 | +Infix = input("\nEnter an Infix Equation = ") #Input an Infix equation |
| 51 | +Infix = "".join(Infix.split()) #Remove spaces from the input |
| 52 | +print("\n\t", Infix, "->", infix_2_postfix(Infix)) |
0 commit comments