Python heapq _heappop_max














































Python heapq _heappop_max



(<-Home)
_heappop_max will pop out the topmost item from heap maintaining maxheap property.

(Click here for full source code)

#This snippet is from heapq class. 'self' refers to heap object

def __siftup_max(self,pos):
"""adjust item at pos to its correct position
and following sub tree, if misplaced"""

heap=self.__heap
child=
2*pos+1 # left child
largest=pos
if child<len(heap) and heap[largest]<heap[child]:
largest=child
if child+1<len(heap) and heap[largest]<heap[child+1]:
largest=child+
1
if largest!=pos:
heap[largest],heap[pos]=heap[pos],heap[largest]
self.__siftup_max(largest)

def _heappop_max(self):
"""remove item from the heap maintaining heap property"""
heap=self.__heap
lastitem=heap.pop()
if heap:
topmost=heap[
0]
heap[
0]=lastitem
self.__siftup_max(
0)
return topmost
return lastitem

For poping, the topmost element is replaced by the last item of heap and topmost
item will be returned at last. '__siftup_max' will then correct the affected branch
thus maintaining the maxheap property.

Consider below example. Here '45' is poped out from maxheap:



## Another Example
raw=[27, 38, 18, 17, 14]
hp=heapq(raw)
hp._heapify_max()
print("poped:",hp._heappop_max())
print("after heappop:",hp)

>>poped: 38
>>after heappop: [27, 17, 18, 14]

Comments