Code Snippet #3: Last In! First Out!

so I felt like doing another basic data structure, so here is the stack.
these code snippets were also originally supposed to be a different language every day but for the sake of simplicity for those who might just now be learning these I'll do them in python to start with, eventually over time I'll will do these data structures again in other languages.

So anyways

In programming, a stack is a simple data structure that follows the Last In, First Out (LIFO) principle. This means that the last element added is the first to be removed.

you have stuff you can do like
Push: Adds an element to the top.
Pop: Removes the top element.
Peek: Views the top element without removal.
Size and isEmpty: Checks the number of elements and if the stack is empty.

I think the most common use of a stack is the undo button that you find in text editors and stuff, I guess each word or letter is stored in a stack and popped out of it.

So here is how to make a Stack in Python!
anyways here is the code if you want to copy it:

how to make a Stack in Python
class Stack:
    def __init__(self):
        """
        makes an empty stack.
        """
        self.items = []

    def is_empty(self) -> bool:
        """
        Checks if the stack is empty.
        Returns:
            bool: True if the stack is empty, False otherwise.
        """
        print(self.items)
        return len(self.items) == 0

    def push(self, item):
        """
        Pushes an item onto the top of the stack.
        Args:
            item: The item to be pushed onto the stack.
        """
        self.items.append(item)
        print(self.items)

    def pop(self):
        """
        Removes and returns the item at the top of the stack.
        Returns:
            Any: The item at the top of the stack, or None if the stack is empty.
        """
        if self.items:
            return self.items.pop()
        else:
            return None
 
    def peek(self):
        """
        Returns the item at the top of the stack without removing it.
        Returns:
            Any: The item at the top of the stack, or None if the stack is empty.
        """
        if self.items:
            return self.items[-1]
        else:
            return None

# Example usage:
stack = Stack()
print("Is the stack empty?", stack.is_empty())
stack.push(10)
stack.push(20)
stack.push(30)
print("Top of the stack:", stack.peek())
print("Stack size:", len(stack.items))
popped_item = stack.pop()
print("Popped item:", popped_item)
print("Is the stack empty?", stack.is_empty())

Code Breakdown:

Class Initialization: The Stack class is initialized with an empty list (self.items) as its underlying data structure.

is_empty Method: This method checks if the stack is empty by examining whether the items list is empty. It returns a boolean value.

push Method: To add an item to the stack, the push method appends the item to the end of the items list.

pop Method: For popping, the pop method removes and returns the item at the top of the items list.

peek Method: The peek method returns the item at the top of the stack without removing it.

Code Execution:

The script demonstrates the usage of the Stack class by creating an instance, pushing items onto the stack, peeking at the top item, popping an item, and checking if the stack is empty at different points.

Application and Learning:

Fundamental Stack Operations: This code provides a solid foundation for understanding and implementing basic stack operations.

Error Handling: The pop and peek methods gracefully handle scenarios where the stack is empty, preventing errors.

Conclusion:

This straightforward stack implementation opens a world of possibilities, including:

Function calls: Python uses a stack to manage function calls, ensuring proper execution order.

Backtracking algorithms: Explore multiple paths in a problem space by backtracking to previous states.

Expression evaluation: Evaluate mathematical expressions in the correct order using a stack.

Undo/redo functionality: Implement features that allow users to revert or repeat actions.

By understanding and utilizing stacks effectively, you'll create more versatile and well-organized code, ready to tackle diverse programming challenges.

Happy coding and happy stacking!

 

Comments

Quote of the day