Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
398: Implementing a Stack and Queue
Think about a stack of cafeteria trays. When the dishwasher puts a clean tray down, it goes right on top. When you come along to grab one for your lunch, you take the one from the top. You'd never try to yank the bottom tray out from under the pile unless you wanted a plastic avalanche on your shoes. That's a Stack: Last-In, First-Out (LIFO).
Now, contrast that with a line at a coffee shop. The first person to arrive is the first person who gets their latte. If the barista started serving the person who just walked in the door while everyone else waited, there would be a riot. That's a Queue: First-In, First-Out (FIFO).
The Cafeteria Tray Logic (Stacks)
In Python, you don't actually need a special library to build a stack. A standard list is surprisingly perfect for this. Because we only care about the "top" of the stack, we use append() to push something on and pop() to take it off. Since pop() defaults to the last item in the list, it's an incredibly efficient operation.
# Using a list as a stack
undo_stack = []
# Pushing "actions" onto the stack
undo_stack.append("Typed 'Hello'")
undo_stack.append("Typed ' World'")
undo_stack.append("Changed font to Bold")
print(f"Current state: {undo_stack}")
# The last thing we did is the first thing we undo
last_action = undo_stack.pop()
print(f"Undoing: {last_action}") # Changed font to Bold
print(f"Remaining stack: {undo_stack}")
I've used an "undo" history here because that's exactly how your favorite text editor works. It doesn't care about the first letter you typed ten minutes ago; it only cares about the very last thing you did.
The Coffee Shop Line (Queues)
Here is where things get tricky. You might be tempted to use a list for a queue, too—using append() to join the line and pop(0) to serve the person at the front. Honestly? Don't do that.
In Python, lists are arrays under the hood. When you pop(0), Python has to shift every single other element in the list one position to the left to fill the gap. If your queue has 10,000 people in it, that's 9,999 movements every time someone is served. It's a performance nightmare.
Instead, we use deque (short for "double-ended queue") from the collections module. It's designed specifically so that adding or removing items from either end happens instantly, regardless of how big the queue is.
from collections import deque
# Creating a queue for a print job
print_queue = deque()
# People sending documents to the printer
print_queue.append("Budget_Report.pdf")
print_queue.append("Vacation_Photos.jpg")
print_queue.append("Resume_Final_v2.docx")
print(f"Queue: {list(print_queue)}")
# Serve the first person in line
current_job = print_queue.popleft()
print(f"Printing: {current_job}") # Budget_Report.pdf
print(f"Remaining queue: {list(print_queue)}")
Choosing the Right Tool for the Job
The choice usually comes down to how you need to access your data. If you're building a feature like a "Back" button in a browser, you want a Stack—you want to go back to the most recent page. If you're building a system to handle incoming web requests or a task scheduler, you want a Queue—you want to process the oldest request first to ensure fairness.
📋 Practical Task
Implementing a Browser Navigation History Manager
You are building a simplified version of a web browser's navigation system. You need to implement a class called BrowserHistory that manages two different data structures: a stack for the "Back" history and a stack for the "Forward" history.
Your requirements:
- Implement a
visit(url)method: This should push the new URL onto theback_stackand clear theforward_stack(since visiting a new page breaks the forward chain). - Implement a
go_back()method: This should pop the current page from theback_stackand push it onto theforward_stack, returning the new current page. - Implement a
go_forward()method: This should pop a page from theforward_stackand push it back onto theback_stack, returning the new current page. - Handle "empty" cases: If the user tries to go back or forward but there is no history, return a string saying "No history available".
Example Workflow:
history = BrowserHistory()
history.visit("google.com")
history.visit("github.com")
history.visit("python.org")
print(history.go_back()) # Should return "github.com"
print(history.go_back()) # Should return "google.com"
print(history.go_forward()) # Should return "github.com"
history.visit("stackoverflow.com")
print(history.go_forward()) # Should return "No history available" (because visit cleared it)
There are no comments for now.