|
| 1 | +def is_operator(op): |
| 2 | + if op=='^' or op=='*' or op=='/' or op=='+' or op=='-': |
| 3 | + return True |
| 4 | + else: |
| 5 | + return False |
| 6 | +def preced(op, stack_op): |
| 7 | + precedence = {'+':1, '-':1, '*':2, '/':2, '^':3} |
| 8 | + try: |
| 9 | + if precedence[op]<=precedence[stack_op]: |
| 10 | + return True |
| 11 | + |
| 12 | + except KeyError: |
| 13 | + return False |
| 14 | +def infix_to_postfix(exp): |
| 15 | + stack, res = [], '' |
| 16 | + for i in exp: |
| 17 | + # Case1: IsOperand() |
| 18 | + if i.isalpha(): |
| 19 | + res += i |
| 20 | + # Case2: IsOpeningParenthesis() |
| 21 | + elif i=='(': |
| 22 | + stack.append(i) |
| 23 | + # Case3: IsClosingParenthesis() |
| 24 | + elif i==')': |
| 25 | + while len(stack)>0 and stack[-1]!='(': |
| 26 | + res += stack.pop() |
| 27 | + if len(stack)>0 and stack[-1]=='(': |
| 28 | + stack.pop() |
| 29 | + # Case4: IsOperator() |
| 30 | + elif is_operator(i): |
| 31 | + while len(stack)>0 and preced(i, stack[-1]): |
| 32 | + res += stack.pop() |
| 33 | + stack.append(i) |
| 34 | + while len(stack)>0: |
| 35 | + res += stack.pop() |
| 36 | + print(res) |
| 37 | + |
| 38 | +for i in range(int(input())): |
| 39 | + infix = input() |
| 40 | + infix_to_postfix(infix) |
0 commit comments