Python heapq _heappush_max














































Python heapq _heappush_max



(<-Home)
_heappush_max(item) will insert an 'item' on the heap maintaining maxheap property.
Look at the code snipet below:
(
click here for full source code)

# This snipet is from heapq class. 'self' refers to heap object.
def _heappush_max(self,item):
"""push item on the heap maintaining heap property"""
heap=self.__heap # object "self.__heap" is assigned to heap for simplicity
heap.append(item) # item is inserted at the end of list
self.__siftdown_max(0,len(heap)-1) # modify list to maintain heap property

def
__siftdown_max(self,start,end):

"""correct a heap by placing element at end to its correct place"""
heap=self.__heap
newitem=heap[end]
while end>start:
parentpos=(end
-1)>>1
parent=heap[parentpos]
if newitem>parent:
heap[end]=parent
end=parentpos
continue
break
heap[end]=newitem

The newly added item should always be appended at the end of current heap. Than,
adjust the heap to maintain the maxheap property as follow:
For the newly inserted element, compare it with its parent. Move down parent at each
node until find the correct place for new element. Insert element at this location.

Consider below example. Here 39 is inserted on maxheap.
##Another Example raw=[27, 38, 18, 17, 14] hp=heapq(raw) hp._heapify_max() hp._heappush_max(15) print("after heappush:",hp) >>after heappush: [38, 27, 18, 17, 14, 15]

Comments