Infix to postfix conversion in Python

mrsan22 picture mrsan22 · Dec 21, 2014 · Viewed 12.6k times · Source

I have started solving Data Structure problems in Python. I am implementing infix to postfix but not able to debug an error in my program. The final return statement where I perform join operation has input of type NONE.

When I started debugging, I found that in this part of code, something is going wrong after the first push operation (for *). After that when I am doing pop() to it's returning NONE instead of returning *. Can someone please point out, what is the mistake 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())*

Infix to Postfix conversion:

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"))

Answer

Tony picture Tony · Dec 21, 2014

Your code works for me, with my own stack implementation.

I get output of ['A', 'B', '*', 'C', 'D', '*', '+'].

I suspect the problem might be in your stack implementation. What does that look like?

Here is mine (suboptimal I am 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