60. Using heapq for Priority Queues
The heapq module in Python provides a way to implement efficient priority queues using heaps. A heap is a specialized tree-based data structure that satisfies the heap property, which ensures that the smallest element is always at the root. Here are several examples of using heapq for priority queues:
1. Basic Priority Queue Implementation
This is the basic implementation of a priority queue using heapq where the smallest element has the highest priority.
Copy
import heapq
# Create an empty list to represent the priority queue
pq = []
# Add items to the queue using heapq.heappush()
heapq.heappush(pq, (2, 'task 2'))
heapq.heappush(pq, (1, 'task 1'))
heapq.heappush(pq, (3, 'task 3'))
# Pop items from the queue using heapq.heappop()
while pq:
priority, task = heapq.heappop(pq)
print(f"Task: {task}, Priority: {priority}")Output:
Copy
In this example, the heappush function is used to insert tasks with their associated priority, and heappop is used to remove and return the task with the highest priority (smallest value).
2. Priority Queue with Custom Priorities
In this example, we implement a priority queue where we control the order by using custom priorities (e.g., a negative priority value to invert the order).
Copy
Output:
Copy
By negating the priority, we ensure that the heapq module uses the smallest value as the highest priority, effectively inverting the order.
3. Using heapq.nlargest() for Top-N Items
You can use heapq.nlargest() to efficiently find the n largest items in a collection, which is a common use case in priority queues.
Copy
Output:
Copy
In this example, nlargest retrieves the top 2 tasks with the highest priority.
4. Using heapq.nsmallest() for Bottom-N Items
Similarly, heapq.nsmallest() allows you to find the n smallest items from a collection.
Copy
Output:
Copy
This example retrieves the bottom 2 tasks with the lowest priority.
5. Using heapq.merge() for Merging Multiple Heaps
If you have multiple heaps and want to merge them into a single sorted iterator, you can use heapq.merge().
Copy
Output:
Copy
The merge() function merges multiple sorted inputs (min-heaps) into a single sorted output.
6. Heap as a Min-Heap
The default behavior of heapq is to create a min-heap. Here’s an example of how you can use heapq to maintain a min-heap.
Copy
Output:
Copy
In this example, heapq ensures that the smallest element is always at the root of the heap.
7. Heap for Sorting Large Data
You can use heapq to efficiently sort large data that might not fit entirely in memory at once.
Copy
This example shows how you can take a large dataset and use a heap to efficiently sort and pop the smallest elements.
8. Heap for Priority Scheduling
You can implement a simple priority scheduling system using a heap.
Copy
Output:
Copy
9. Finding Kth Largest Element
You can use heapq.nlargest() to find the Kth largest element in a list.
Copy
Output:
Copy
10. Heap for Dijkstra’s Shortest Path Algorithm
A priority queue is often used in algorithms like Dijkstra’s to efficiently get the smallest edge weight.
Copy
Output:
Copy
Last updated