Python: Delete the smallest element from the given Heap and then inserts a new item
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 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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics