STACK IMPLEMENT IN PYTHON

 STACK

class stack:
    def __init__(self):
        self.fb=0
        self.sb=0
        self.tb=0
        self.top=0
        self.stack=[]
        self.maxx=int(input("Enter the array size: "))
        
    def pushh(self,item):
        self.top+=1
        self.stack.append(item)
        
    def popp(self):
        if self.top!=0:
            self.top-=1
            print (self.stack.pop())
        else:
            print ("stack underflow")
            
    def display(self):
        if self.top!=0:
            print (self.stack)
        else:
            print("StacK underflow")
    
s1=stack()
while(True):
    print("\n\n1. display")
    print("2. Pop top element" )
    print("3. push an element")
    print("4. check balanced or not")
    print("5. exit")
    ch=int(input("Enter the choice: "))
    if ch==1:
        s1.display()
    elif ch==2:
        s1.popp()        
    elif ch==3:
        if s1.top<s1.maxx:
            m=input("Enter String: ")
            print( type(m))
            s1.pushh(m)
        else:
            print("stack overflow")
    elif ch==4:

        for i in s1.stack:
            if i=='(':
                s1.fb+=1
            elif i==')':
                s1.fb-=1
            elif i=='[':
                s1.tb+=1
            elif i==']':
                s1.tb-=1
            elif i=='{':
                s1.sb+=1
            elif i=='}':
                s1.sb-=1

        if s1.fb==0 and s1.tb==0 and s1.sb==0:
            print( "BALANCED STACK")
        else:
            print ("NOT BALANCED STACK")
    else:
        exit()

Comments

Popular posts from this blog

PALINDROME NUMBER

CONVERT CARTESIAN COORDINATES TO POLAR COORDINATE

FIBONACCI SERIES