w3resource

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

Python heap queue algorithm: Exercise-5 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/heap-queue-algorithm/python-heapq-exercise-5.php