w3resource

Python: Delete the smallest element from the given Heap and then inserts a new item


5. Heap Update (Delete and Insert)

Write a Python program that deletes the smallest element from a heap and then inserts a new item.

Sample Solution:

Python Code:

import heapq as hq

heap = [25, 44, 68, 21, 39, 23, 89]
hq.heapify(heap)
print("heap: ", heap)
hq.heapreplace(heap, 21)
print("heapreplace(heap, 21): ", heap)
hq.heapreplace(heap, 110)
print("heapreplace(heap, 110): ", heap)

Sample Output:

heap:  [21, 25, 23, 44, 39, 68, 89]
heapreplace(heap, 21):  [21, 25, 23, 44, 39, 68, 89]
heapreplace(heap, 110):  [23, 25, 68, 44, 39, 110, 89]

Flowchart:

Python heap queue algorithm: Delete the smallest element from the given Heap and then inserts a new item.

For more Practice: Solve these Related Problems:

  • Write a Python program to delete the smallest element from a heap using heapq.heappop and then insert a new element using heapq.heappush, printing the heap before and after.
  • Write a Python script to update a heap by removing the minimum element and then adding a new number, ensuring the heap property is maintained.
  • Write a Python function to simulate a heap update by performing a delete-min followed by an insertion and then output the modified heap.
  • Write a Python program to remove the smallest value from a heap, insert a new value, and then print both the removed element and the updated heap structure.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python function which accepts an arbitrary list and converts it to a heap using Heap queue algorithm.
Next: Write a Python program to sort a given list of elements in ascending order using Heap queue algorithm.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.