Introduction
Imagine you have a list of tasks, but some tasks are more urgent than others. You want a way to always pick the most important task first without sorting the whole list every time. This is the problem that a priority queue solves.
Imagine a hospital emergency room where patients arrive with different levels of urgency. Instead of treating patients in the order they arrive, doctors treat the most critical patients first. This way, the most urgent cases get attention quickly.
┌───────────────┐ │ Priority Queue│ ├───────────────┤ │ [Task A, 5] │ ← Highest priority (5) │ [Task B, 3] │ │ [Task C, 1] │ ← Lowest priority (1) └───────────────┘ Operations: Insert → Places task by priority Remove → Takes out highest priority task
import heapq class PriorityQueue: def __init__(self): self._heap = [] def insert(self, item, priority): # Use negative priority because heapq is a min-heap heapq.heappush(self._heap, (-priority, item)) def remove(self): if self._heap: priority, item = heapq.heappop(self._heap) return item return None pq = PriorityQueue() pq.insert('Task A', 5) pq.insert('Task B', 3) pq.insert('Task C', 1) print(pq.remove()) # Should print 'Task A' print(pq.remove()) # Should print 'Task B' print(pq.remove()) # Should print 'Task C'