Code Explanation:
1) import heapq
Imports Python’s heapq module, which implements a min-heap using lists.
A min-heap always keeps the smallest element at index 0.
2) nums = [5, 1, 8, 3]
Defines a normal Python list with values [5, 1, 8, 3].
Not yet a heap — just a plain list.
3) heapq.heapify(nums)
Converts the list in-place into a valid min-heap.
After heapify, the smallest element moves to the front.
Internal structure may change, but order is not guaranteed beyond the heap property.
Now nums becomes [1, 3, 8, 5].
(smallest element 1 at index 0).
4) heapq.heappush(nums, 0)
Pushes 0 into the heap while maintaining the heap property.
Since 0 is the new smallest element, it bubbles up to the root.
Now nums = [0, 1, 8, 5, 3].
5) print(heapq.heappop(nums), nums[0])
heapq.heappop(nums) → removes and returns the smallest element (0).
After popping, the heap readjusts, so the next smallest element (1) becomes root.
nums[0] → now points to the new smallest element (1).
Final Output
0 1
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment