(Postfix)
| 20 | import operator as op |
| 21 | |
| 22 | def Solve(Postfix): |
| 23 | Stack = [] |
| 24 | Div = lambda x, y: int(x/y) # integer division operation |
| 25 | Opr = {'^':op.pow, '*':op.mul, '/':Div, '+':op.add, '-':op.sub} # operators & their respective operation |
| 26 | |
| 27 | # print table header |
| 28 | print('Symbol'.center(8), 'Action'.center(12), 'Stack', sep = " | ") |
| 29 | print('-'*(30+len(Postfix))) |
| 30 | |
| 31 | for x in Postfix: |
| 32 | if( x.isdigit() ): # if x in digit |
| 33 | Stack.append(x) # append x to stack |
| 34 | print(x.rjust(8), ('push('+x+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format |
| 35 | else: |
| 36 | B = Stack.pop() # pop stack |
| 37 | print("".rjust(8), ('pop('+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format |
| 38 | |
| 39 | A = Stack.pop() # pop stack |
| 40 | print("".rjust(8), ('pop('+A+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format |
| 41 | |
| 42 | Stack.append( str(Opr[x](int(A), int(B))) ) # evaluate the 2 values poped from stack & push result to stack |
| 43 | print(x.rjust(8), ('push('+A+x+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format |
| 44 | |
| 45 | return int(Stack[0]) |
| 46 | |
| 47 | |
| 48 | if __name__ == "__main__": |
no test coverage detected