Queue Basics
""" QUEUES - BASICS
-------------------
A queue is a collection with restricted access (just like a stack):
- You can only add items to the BACK
- You can only remove items from the FRONT
- Very fast O(1) operations
This rule is called FIFO:
- First In, First Out
It's like:
- A line at a movie theater
- Print jobs
Python provides a proper queue structure in its standard library.
Example:
- Print queue using deque
--------------------------
"""
from collections import deque
# Initialize and empty queue
print_queue = deque()
# Documents arrive
print_queue.append("report.pdf")
print_queue.append("invoice.docx")
print_queue.append("photo.png")
print("Queue:", print_queue)
# --------------------------------------------------------
# Queue: deque(['report.pdf', 'invoice.docx', 'photo.png'])
# Printer prints the next document
job = print_queue.popleft()
print(job) # report.pdf
job = print_queue.popleft()
print(job) # invoice.docx
print("Queue:", print_queue)
# --------------------------
# Queue: deque(['photo.png'])
Custom Queue
""" CUSTOM QUEUE
----------------
Queue isn't implemented in many programming language.
Example:
- We create a queue to see how it works internally.
- This is for educational purpose
----------------------------------
"""
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
# Add item to the back of the queue
self.items.append(item)
def dequeue(self):
# Remove item from the front of the queue
if not self.items:
return None
return self.items.pop(0)
def peek(self):
# Read first item without removing it
if not self.items:
return None
return self.items[0]
def __str__(self):
return str(self.items)
# 1) Create queue
# ---------------
queue = Queue()
# 2) Add elements
# ---------------
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue) # [1, 2, 3]
# 3) Remove from front
# --------------------
removed = queue.dequeue()
print("Removed:", removed)
print("Queue:", queue)
print("New front:", queue.peek())
# ----------
# Removed: 1
# Queue: [2, 3]
# New front: 2