Thursday, July 25, 2024

Nitheen Kumar

Implement a stack data structure with push pop peek operations in Python

Here's a simple implementation of a stack data structure in Python using a list:

class Stack:

    def __init__(self):

        self.items = []


    def push(self, item):

        self.items.append(item)


    def pop(self):

        if not self.is_empty():

            return self.items.pop()

        else:

            raise IndexError("pop from empty stack")


    def peek(self):

        if not self.is_empty():

            return self.items[-1]

        else:

            return None


    def is_empty(self):

        return len(self.items) == 0


    def size(self):

        return len(self.items)



Implement a stack data structure with push pop and peek operations in Python

Explanation:

  1. Initialization (__init__ method):

    • Initializes an empty list self.items which will be used to store the elements of the stack.
  2. Push operation (push method):

    • Appends (pushes) an item to the end of the list (self.items).
  3. Pop operation (pop method):

    • Removes and returns the last item from self.items if the stack is not empty. If the stack is empty, it raises an IndexError.
  4. Peek operation (peek method):

    • Returns the last item from self.items without removing it, if the stack is not empty. If the stack is empty, it returns None.
  5. is_empty method:

    • Checks if self.items is empty and returns True if it is, False otherwise.
  6. size method:

    • Returns the number of elements currently in the stack (len(self.items)).

Example Usage:


# Create a new stack
stack = Stack()

# Push some elements onto the stack
stack.push(1)
stack.push(2)
stack.push(3)

# Peek at the top element of the stack
print("Top of the stack:", stack.peek())  # Output: 3

# Pop an element from the stack
print("Popped element:", stack.pop())  # Output: 3

# Check if the stack is empty
print("Is the stack empty?", stack.is_empty())  # Output: False

# Get the size of the stack
print("Size of the stack:", stack.size())  # Output: 2

This implementation provides basic operations (push, pop, and peek) commonly used in stack data structures. Adjustments can be made depending on specific requirements or constraints of the problem at hand.
Subscribe to get more Posts :