Transform the algebraic expression with brackets into RPN form (Reverse
Polish Notation). Two-argument operators: +, -, *, /, ^ (priority from
the lowest to the highest), brackets ( ). Operands: only letters:
a,b,...,z. Assume that there is only one RPN form (no expressions like
a*b*c).
Input
t [the number of expressions <= 100] expression [length <= 400] [other expressions]
Text grouped in [ ] does not appear in the input file.
Output
The expressions in RPN form, one per line.
Example
Input: 3 (a+(b*c)) ((a+b)*(z+x)) ((a+t)*((b+(a+c))^(c+d))) Output: abc*+ ab+zx+* at+bac++cd+^*
Solution (in Python)
import sys def infixtopostfix(exp): output = "" stack = [] op_key = {'+':0,'-':0,'*':1,'/':2,'^':3} for i in range(0,len(exp)): if(exp[i] in op_key.keys()): while(len(stack)>0 and stack[len(stack)-1] != '(' and op_key[exp[i]]<=stack[len(stack)-1]): output += stack.pop() stack.append(exp[i]) elif exp[i] == '(': stack.append('(') elif exp[i] == ')': while(len(stack)>0 and stack[len(stack)-1]!='('): output += stack.pop() if(len(stack)>0): stack.pop() else: output += exp[i] return output T = int(input()) output_list = [] #print Twhile T>0: exp = sys.stdin.readline() exp = exp.strip("\n") output_list.append(infixtopostfix(exp)) T-=1 for i in range(0,len(output_list)): print output_list[i]
No comments:
Post a Comment