tc = int(raw_input())
while tc:
q = str(raw_input())
q = list(q)
stack = []
post = []
stack.append('(')
q.append(')')
length = len(q)
i = 0
while i < length:
if q[i] == '(':
stack.append(q[i])
elif q[i] == ')':
while 1 and len(stack) != 0:
temp = stack.pop()
if temp == '(':
break
else:
post.append(temp)
elif q[i] == '+' or q[i] == '-' or q[i] == '*' or q[i] == '/' or q[i] == '^':
if q[i] == '^':
stack.append(q[i])
elif q[i] == '*' or q[i] == '/':
while 1 and len(stack) != 0:
temp = stack.pop()
if temp == '^' or temp == '*' or temp == '/':
post.append(temp)
else:
stack.append(temp)
stack.append(q[i])
break
elif q[i] == '+' or q[i] == '-':
while 1 and len(stack) != 0:
temp = stack.pop()
if temp == '^' or temp == '*' or temp == '/' or temp == '+' or temp == '-':
post.append(temp)
else:
stack.append(temp)
stack.append(q[i])
break
elif q[i] >= 'a' and q[i] <= 'z':
post.append(q[i])
i = i + 1
tc = tc - 1
print "".join(post)
Be Pythonic
Friday, January 14, 2011
4. Transform the Expression
Code:
Labels:
classical,
infix-to-postfix
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment