126. Complex Data Structures with heapq
The heapq module in Python provides a way to implement priority queues using heaps. A heap is a specialized tree-based data structure that satisfies the heap property, where the parent node is smaller (in a min-heap) or larger (in a max-heap) than its children. The heapq module specifically implements a min-heap by default, but max-heaps can be simulated.
Here are 10 Python code snippets demonstrating the use of heapq to manage complex data structures like priority queues.
1. Basic Min-Heap Usage
Copy
import heapq
heap = []
heapq.heappush(heap, 20)
heapq.heappush(heap, 5)
heapq.heappush(heap, 15)
print(heap) # Output: [5, 20, 15]
print(heapq.heappop(heap)) # Output: 5
print(heap) # Output: [15, 20]2. Max-Heap Simulation with Negatives
Copy
import heapq
max_heap = []
heapq.heappush(max_heap, -20)
heapq.heappush(max_heap, -5)
heapq.heappush(max_heap, -15)
print([-item for item in max_heap]) # Output: [20, 5, 15]
print(-heapq.heappop(max_heap)) # Output: 20
print([-item for item in max_heap]) # Output: [15, 5]3. Priority Queue with Custom Objects
Copy
4. Heapq for Sorting
Copy
5. Heapq with heapreplace to Replace Minimum Element
Copy
6. Efficient Merging of Multiple Sorted Lists
Copy
7. Find the N Largest Elements in a List
Copy
8. Find the N Smallest Elements in a List
Copy
9. Custom Priority Queue with Tuple and Custom Comparator
Copy
10. Kth Smallest Element in a Stream
Copy
These examples demonstrate various ways to use the heapq module for implementing efficient priority queues, merging sorted data, finding largest or smallest elements, and more complex applications with custom objects. The heapq module is especially useful when you need to manage a dynamic collection of elements and perform fast retrieval of the smallest or largest elements in the collection.
Last updated