0
>>> import heapq as h
>>> l = [1,3,6,2,9]
>>> dir(h) ['__about__', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__', '_heapify_max', '_heappop_max', '_heapreplace_max',
'_siftdown', '_siftdown_max', '_siftup', '_siftup_max', 'heapify',
'heappop', 'heappush', 'heappushpop', 'heapreplace', 'merge',
'nlargest', 'nsmallest']
>>> h._heapify_max(l)
>>> l [9, 3, 6, 2, 1]
>>> l [1, 3, 6, 2]
>>> h.heappush(l,9)
>>> l [1, 3, 6, 2, 9]
>>> h._heapify_max(l)
>>> l [9, 3, 6, 2, 1]
>>> h._heappop_max(l) 9
>>> l [6, 3, 1, 2]
>>> h.heappush(l,9)
>>> l [6, 3, 1, 2, 9]
>>>

after this how should I insert 9 that it comes to the actual position i.e. the 0th index?

  • `heapq` implements a *min heap*, see [here](https://docs.python.org/3/library/heapq.html?#module-heapq). Smaller values at top (index 0). – progmatico Nov 03 '20 at 14:27
  • 2
    Attributes beginning with a ``_`` are a sure sign that you should *not* use them unless you know what you are doing. The naive approach to having the min heap ``heapq`` as a "max heap" is to invert each value, i.e. store the *negative* values in the heap. – MisterMiyagi Nov 03 '20 at 14:31

0 Answers0