PYTHON
Manage Priority Queues with Python's `heapq` Module
Efficiently implement a min-heap or priority queue in Python using the `heapq` module, ideal for scheduling and top-N element retrieval.
import heapq
# Create an empty min-heap
min_heap = []
# Add elements to the heap (pushes maintain heap property)
heapq.heappush(min_heap, 4)
heapq.heappush(min_heap, 1)
heapq.heappush(min_heap, 7)
heapq.heappush(min_heap, 3)
print(f"Heap after pushes: {min_heap}") # Internal representation is not strictly sorted
# Get the smallest element (pop maintains heap property)
smallest = heapq.heappop(min_heap)
print(f"Smallest element popped: {smallest}")
print(f"Heap after first pop: {min_heap}")
smallest = heapq.heappop(min_heap)
print(f"Next smallest element popped: {smallest}")
print(f"Heap after second pop: {min_heap}")
# Find the N smallest/largest elements efficiently
data = [1, 3, 5, 7, 2, 4, 6, 8, 0]
three_largest = heapq.nlargest(3, data)
three_smallest = heapq.nsmallest(3, data)
print(f"Original data: {data}")
print(f"Three largest elements: {three_largest}")
print(f"Three smallest elements: {three_smallest}")
How it works: This snippet introduces Python's `heapq` module, which provides an implementation of the heap queue algorithm, also known as the priority queue. It uses a regular list as the underlying data structure and provides functions like `heappush` to add elements and `heappop` to remove the smallest element efficiently (O(log n)). It also demonstrates `nlargest` and `nsmallest` for quickly finding the top N elements without fully sorting, useful for leaderboards or resource allocation.