import heapq # Create an empty list that will serve as our min-heap min_heap = [] # Add elements to the heap 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}") # Heap property, not necessarily fully sorted # Get the smallest element (without removing it) print(f"Smallest element: {min_heap[0]}") # Extract the smallest element smallest = heapq.heappop(min_heap) print(f"Popped smallest: {smallest}, Heap remaining: {min_heap}") # Popping again smallest = heapq.heappop(min_heap) print(f"Popped smallest: {smallest}, Heap remaining: {min_heap}") # Heapify an existing list (in-place) data = [10, 2, 8, 5, 12] heapq.heapify(data) print(f"List after heapify: {data}") # Heap property # Example: Finding the N smallest elements k_smallest = heapq.nsmallest(2, [10, 2, 8, 5, 12, 1]) print(f"2 smallest elements: {k_smallest}") # Example: Finding the N largest elements k_largest = heapq.nlargest(2, [10, 2, 8, 5, 12, 1]) print(f"2 largest elements: {k_largest}")