1. Importing the heapq Module
import heapq
Imports Python’s heapq library.
Provides functions to work with heaps (priority queues).
By default, it creates a min-heap (smallest element always at root).
2. Creating a List
nums = [9, 4, 7, 2]
A normal Python list with values [9, 4, 7, 2].
Not yet a heap — just an unordered list.
3. Converting List into a Heap
heapq.heapify(nums)
Transforms the list into a min-heap in place.
Now, nums is rearranged so that the smallest element (2) is at index 0.
Heap after heapify: [2, 4, 7, 9].
4. Adding a New Element to the Heap
heapq.heappush(nums, 1)
Pushes 1 into the heap while maintaining heap order.
Heap now becomes: [1, 2, 7, 9, 4] (internally ordered as a heap, not a sorted list).
5. Removing the Smallest Element
smallest = heapq.heappop(nums)
Pops and returns the smallest element from the heap.
Removes 1 (since min-heap always gives the smallest).
Now, smallest = 1.
Heap after pop: [2, 4, 7, 9].
6. Finding the Two Largest Elements
largest_two = heapq.nlargest(2, nums)
Returns the 2 largest elements from the heap (or any iterable).
Heap currently is [2, 4, 7, 9].
The two largest are [9, 7].
7. Printing Results
print(smallest, largest_two)
Prints the values of smallest and largest_two.
Final Output
1 [9, 7]
.png)

0 Comments:
Post a Comment