Pages

Sunday 7 February 2016

Stack Operations in Python

#program for stack operations
def isempty(stk) :
    if len(stk)==0 :
        return True
    else :
        return False
def PUSH(stk) :
    x=[]
    n=raw_input("Enter Your Name : ")
    no=int(raw_input("Enter Your Number"))
    x.append(n)
    x.append(no)
    stk.append(x)       #x Stores the data in list [Name,Number]
    return stk
def POP(stk) :
    if isempty(stk) :
        print "Empty Stack"
    else :
        x=stk.pop()
        return x
def DISPLAY(stk) :
    y=len(stk)
    z=y
    for i in range(y) :
        if i==0 :
            x=POP(stk)
            print "Item number",z,"is",x,"<----Top"
            z=z-1
        elif i==y-1 :
            x=POP(stk)
            print "Item number",z,"is",x,"<----Bottom"
            z=z-1
        elif i!=0 :
            x=POP(stk)
            print "Item number",z,"is",x
            z=z-1
        no=x.pop()
        n=x.pop()
        print "Name : ",n
        print "Number : ",no
stk=[['Anurag', 9958220446],['Ayush', 8138987125],['Jagrat', 9956288854]]
while True :
    print """Choose from the following menu : -
1) PUSH
2) POP
3) DISPLAY
4) EXIT"""
    ch=int(raw_input("Enter Your Choice : "))
    if ch==1 :
        PUSH(stk)
    elif ch==2 :
        if isempty(stk) :
            x=None
            print "Empty Stack"
        else :
            x=POP(stk)
            print x,"is the popped item."   #To show the popped data
            no=x.pop()
            n=x.pop()
            print "Name : ",n
            print "Number : ",no
    elif ch==3 :
        DISPLAY(stk)
    else :
        break