Introduction
Greetings, aspiring programmers! Today, we’re delving into the world of stacks—a fundamental data structure with a plethora of applications. Whether you’re exploring algorithms or building sophisticated systems, understanding the stack is a valuable asset. In this blog post, we’ll demystify the stack, explore its characteristics, and guide you through the process of implementing a stack in Python with hands-on code examples.
The Essence of a Stack
A stack is a Last In, First Out (LIFO) data structure, resembling a collection of items stacked one on top of another. Imagine a stack of books; the last book placed on the stack is the first one to be removed.
Key Features of a Stack
Before we dive into implementation, let’s outline the key features of a stack:
Push Operation: Adds an element to the top of the stack.
Pop Operation: Removes the element from the top of the stack.
Peek/Top Operation: Retrieves the element at the top of the stack without removing it.
isEmpty Operation: Checks if the stack is empty.
Implementing a Stack in Python
Now, let’s bring the stack to life in Python. We’ll create a simple class encapsulating the stack operations.
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
def peek(self):
if not self.is_empty():
return self.items[-1]
def size(self):
return len(self.items)
Exploring the Stack Operations
Let’s unravel the magic of stack operations using our implemented class.
1. Creating a Stack
stack = Stack()
2. Pushing Elements onto the Stack
stack.push(1)
stack.push(2)
stack.push(3)
3. Checking if the Stack is Empty
print("Is the stack empty?", stack.is_empty())
4. Popping Elements from the Stack
popped_item = stack.pop()
print("Popped item:", popped_item)
5. Peeking at the Top Element
top_item = stack.peek()
print("Top item:", top_item)
6. Checking the Size of the Stack
stack_size = stack.size()
print("Size of the stack:", stack_size)
Real-world Example: Checking Balanced Parentheses
One practical application of a stack is checking whether a given expression has balanced parentheses. Let’s use our stack to implement this.
def is_balanced(expression):
stack = Stack()
for char in expression:
if char in '({[':
stack.push(char)
elif char in ')}]':
if stack.is_empty():
return False
top = stack.pop()
if (char == ')' and top != '(') or \
(char == '}' and top != '{') or \
(char == ']' and top != '['):
return False
return stack.is_empty()