PYTHON
Implement a Priority Queue for Task Management
Use Python's `heapq` module to implement an efficient priority queue, useful for managing tasks, events, or jobs based on their priority level.
import heapq
# A min-heap (smallest item has highest priority)
# Items are tuples: (priority, task_description)
priority_queue = []
heapq.heappush(priority_queue, (3, 'Low priority task'))
heapq.heappush(priority_queue, (1, 'High priority task'))
heapq.heappush(priority_queue, (2, 'Medium priority task'))
heapq.heappush(priority_queue, (1, 'Another high priority task')) # Same priority
print(f"Queue after pushes: {priority_queue}")
# Output will vary in order for same priority, but lowest priority always at index 0:
# e.g., [(1, 'High priority task'), (1, 'Another high priority task'), (2, 'Medium priority task'), (3, 'Low priority task')]
# Pop items (smallest priority first)
print(f"Processing: {heapq.heappop(priority_queue)}") # (1, 'High priority task')
print(f"Processing: {heapq.heappop(priority_queue)}") # (1, 'Another high priority task')
# You can peek at the smallest item without removing it
if priority_queue:
print(f"Next to process: {priority_queue[0]}") # (2, 'Medium priority task')
print(f"Remaining queue: {priority_queue}")
# Output: Remaining queue: [(2, 'Medium priority task'), (3, 'Low priority task')]
How it works: The `heapq` module in Python provides an implementation of the heap queue algorithm, commonly known as a priority queue. It efficiently maintains a min-heap, ensuring that the smallest item (based on the first element of a tuple, if items are tuples) can always be retrieved quickly. This data structure is vital for applications requiring tasks to be processed based on their urgency, such as job schedulers, event managers, or network routers, guaranteeing that critical operations are handled with precedence.