Infix for postfix conversion in Python
I started to solve problems with data structure in Python. I am using infix for postfix, but cannot debug a bug in my program. The final return statement in which I perform the join operation has an input of type NONE.
When I started debugging, I found that something was wrong in this part of the code after the first push operation (for *). After that, when I do pop (), it returns NONE instead of returning *. Can someone please point out that there is a bug here?
*else:
while (not s.isEmpty()) and (prec[s.peek()] >= prec[token]):
#print token
outlst.append(s.pop())
#print outlst
s.push(token)
print (s.peek())*
Converting Infix to Postfix:
from StackClass import StackClass
def infixtopostfix(infixexpr):
s=StackClass()
outlst=[]
prec={}
prec['/']=3
prec['*']=3
prec['+']=2
prec['-']=2
prec['(']=1
oplst=['/','*','+','-']
tokenlst=infixexpr.split()
for token in tokenlst:
if token in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or token in '0123456789':
outlst.append(token)
elif token == '(':
s.push(token)
elif token == ')':
topToken=s.pop()
while topToken != '(':
outlst.append(topToken)
topToken=s.pop()
else:
while (not s.isEmpty()) and (prec[s.peek()] >= prec[token]):
#print token
outlst.append(s.pop())
#print outlst
s.push(token)
print (s.peek())
while not s.isEmpty():
opToken=s.pop()
outlst.append(opToken)
#print outlst
return outlst
#return " ".join(outlst)
print (infixtopostfix("A * B + C * D"))
+3
source to share
1 answer
Your code works for me, with my own stack implementation.
I am getting output ['A', 'B', '*', 'C', 'D', '*', '+']
.
I suspect the problem might be with your stack implementation. What does it look like?
Here's mine (suboptimal, I'm sure!):
class StackClass:
def __init__(self, itemlist=[]):
self.items = itemlist
def isEmpty(self):
if self.items == []:
return True
else:
return False
def peek(self):
return self.items[-1:][0]
def pop(self):
return self.items.pop()
def push(self, item):
self.items.append(item)
return 0
+2
source to share