i am converting infix to postfix.. but when i try to read expressions from file (line by line). its just giving me not what i want.
Code:
postfix = []
temp = []
operator = -1
operand = -2
leftparent = -3
rightparent = -4
empty = -5
def precedence(s):
if s is '(':
return 0
elif s is '+' or '-':
return 1
elif s is '*' or '/' or '%':
return 2
else:
return 99
def typeof(s):
if s is '(':
return leftparent
elif s is ')':
return rightparent
elif s is '+' or s is '-' or s is '*' or s is '%'or s is '/':
return operator
elif s is ' ':
return empty
else :
return operand
lines = [line.strip() for line in open('tem')]
for i in line :
type = typeof(i)
if type is leftparent :
temp.append(i)
elif type is rightparent :
next = temp.pop()
while next is not '(':
postfix.append(next)
next = temp.pop()
elif type is operand:
postfix.append(i)
elif type is operator:
p = precedence(i)
while len(temp) is not 0 and p <= precedence(temp[-1]) :
postfix.append(temp.pop())
temp.append(i)
elif type is empty:
continue
while len(temp)>0:
postfix.append(temp.pop())
print "It's postfix notation is ",' '.join(postfix)