Heapreplace function of heapq module in python

Overview:

  • The min heap created by the heapq.heapify() maintains the lowest element of the heap at the root.
  • The heaprepalce() function of the Python heapq module pops the element at the root node and inserts an element into the min heap while maintaining the heap invariants.

Example:

# Example Python program that pops an item and pushes another item

# using heapq.heapreplace() function

import heapq

 

# Construct a heap

elems = [1, 7, 3, 5, 2, 11, 19, 17, 13]

heapq.heapify(elems)

print("The initial heap is:")

print(elems)

 

print("Largest %d elements:"%len(elems))

sorted = heapq.nsmallest(len(elems), elems)

print(sorted)

 

# pop and replace once

heapq.heapreplace(elems, 23)

print("After calling heapreplace once")

print(elems)

 

# pop and replace again

heapq.heapreplace(elems, 29)  

print("After calling heapreplace again")

print(elems)

 

Output:

The initial heap is:

[1, 2, 3, 5, 7, 11, 19, 17, 13]

Largest 9 elements:

[1, 2, 3, 5, 7, 11, 13, 17, 19]

After calling heapreplace once

[2, 5, 3, 13, 7, 11, 19, 17, 23]

After calling heapreplace again

[3, 5, 11, 13, 7, 29, 19, 17, 23]


Copyright 2024 © pythontic.com