Stack with Python

admin
By -
0

Here we trying to implement Stack data structure e FILO through using some built-in in python function and simple list indices and top variable


Both codes implement a Stack data structure using a Python list. The main difference is how they keep track of the "top" element.


Here are the step-by-step breakdowns for each:


Code #1: Without top Variable

This version relies entirely on Python’s built-in list functions (like len() and negative indexing) to manage the stack.


Initialization: Creates an empty list and sets a max_size.


Push Step: 1. Checks if the current length of the list is less than max_size.


2. If true, it uses .append() to add the value to the end.


3. If false, it prints "Stack is overflow."


Pop Step: 1. Checks if the list is empty.


2. If not, it removes the last item using .pop().


3. It then returns the new last item using index [-1]. (Note: This logic is slightly unusual, as most pops return the item just removed, not the one below it).


Peek Step: Simply looks at index [-1] to see the last item added.


Empty Check: Uses len(self.stack) == 0 to determine if the stack is empty.




Code-#1


'''Without Top variable '''


class Tack:


    def __init__(self, max_size):


        self.stack = []


        self.max_size = max_size


        #self.top = -1


    


    def push(self,value):


        if len(self.stack) < self.max_size:


            self.stack.append(value)


            #self.top += 1  # Increment top


            #print(value)


        else:


            print("Stack is overflow")




    def pop(self):


        if self.isEmpty():


            print("Stack is empty")


            return None


        else:


            self.stack.pop()


            #self.top -= 1  # Decreancrement top


            return self.stack[-1]


        




            


    def peek_top(self):


        #return self.stack[self.top]


        return self.stack[-1]


            


        


    def isEmpty(self):


        return True if len(self.stack) == 0 else False


    


  


        


        


st = Tack(max_size=8)


import random


for _ in range(11):


    st.push(random.randint(1,20))


    


print("Stack",st.stack)


print("Peeak",st.peek_top())




print("Pop",st.pop())


    


print("Stack",st.stack)


print("pop",st.pop())




print("Stack",st.stack)












Code #2: With top Variable

This version uses a manual pointer (self.top) to track the index of the highest element, similar to how stacks are managed in languages like C or Java.


Initialization: Creates an empty list, sets max_size, and initializes self.top to -1 (meaning the stack is empty).


Push Step: 1. Checks if self.top is less than max_size - 1.


2. If true, it appends the value and manually increments self.top by 1.


3. If false, it prints "Stack is overflow."


Pop Step: 1. Checks if the stack is empty.


2. If not, it removes the last item and manually decrements self.top by 1.


3. It returns the item located at the new self.top index.


Peek Step: Returns the item at the specific index stored in self.top.


Empty Check: Still uses the list length, though it could also use if self.top == -1.



Code #2


class Tack:

    def __init__(self, max_size):

        self.stack = []

        self.max_size = max_size

        self.top = -1

    

    def push(self,value):

        if self.top < self.max_size - 1:

            self.stack.append(value)

            self.top += 1  # Increment top

            #print(value)

        else:

            print("Stack is overflow")


    def pop(self):

        if self.isEmpty():

            print("Stack is empty")

            return None

        else:

            self.stack.pop()

            self.top -= 1  # Decreancrement top

            return self.stack[self.top]

        


            

    def peek_top(self):

        return self.stack[self.top]

        #return self.stack[-1]

            

        

    def isEmpty(self):

        return True if len(self.stack) == 0 else False

    

  

        

        

st = Tack(max_size=8)

import random

for _ in range(11):

    st.push(random.randint(1,20))

    

print("Stack",st.stack)

print("Peeak",st.peek_top())


print("Pop",st.pop())

    

print("Stack",st.stack)

print("pop",st.pop())


print("Stack",st.stack)







Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*