FACTORIAL USING STACK

FACTORIAL USING STACK

class stack:
    def __init__(self):
        self.top=0
        self.stack=[]
        self.m=0
        
    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")
    
    def factorialx(self):
        for i in range(1,self.m +1 ):
            self.stack.append(i)
        n=1    
        for i in range(self.m,0,-1):
            n=n*self.stack.pop()
        return n    
            
s1=stack()
while(True):
    print("\n\n1. Enter value: " )
    print("2. Factorial")
    print("4. exit")
    ch=int(input("Enter the choice: "))
    if ch==1:
        s1.m=int(input("Enter the value: "))
    elif ch==2:
        print(s1.factorialx())
        print(s1.stack)
    else:
        exit()

Comments

Popular posts from this blog

SAME NAME IN CLASS METHOD AND CONSTRUCTOR

PALINDROME NUMBER

FIBONACCI SERIES