import heapq # A min-heap (default behavior) priority_queue = [] # Add items to the priority queue # Items are tuples: (priority, data) heapq.heappush(priority_queue, (3, "task C")) heapq.heappush(priority_queue, (1, "task A")) heapq.heappush(priority_queue, (2, "task B")) heapq.heappush(priority_queue, (0, "task Z")) print(f"Heap after adding items (internal representation): {priority_queue}") # Pop items from the priority queue (smallest priority first) print(f"Processing highest priority item: {heapq.heappop(priority_queue)}") print(f"Processing next highest priority item: {heapq.heappop(priority_queue)}") # Example of using heapq.heapify on an existing list data = [(5, "item E"), (1, "item A"), (4, "item D"), (2, "item B"), (3, "item C")] heapq.heapify(data) # Transforms list into a heap in-place print(f"Heapified list: {data}") print(f"Processing from heapified list: {heapq.heappop(data)}") # Finding the N smallest/largest items efficiently numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] print(f"3 smallest numbers: {heapq.nsmallest(3, numbers)}") print(f"3 largest numbers: {heapq.nlargest(3, numbers)}")