w3resource

Python Exercise: Pushing all values onto a heap and then popping off the smallest values one at a time

Python heap queue algorithm: Exercise-3 with Solution

Write a Python program to implement a heapsort by pushing all values onto a heap and then popping off the smallest values one at a time.

Sample Solution:

Python Code:

import heapq as hq
def heapsort(iterable):
    h = []
    for value in iterable:
        hq.heappush(h, value)
    return [hq.heappop(h) for i in range(len(h))]
print(heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]))

Sample Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Flowchart:

Python heap queue algorithm: Pushing all values onto a heap and then popping off the smallest values one at a time.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

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

Previous: Write a Python program to find the three smallest integers from a given list of numbers using Heap queue algorithm.
Next: Write a Python function which accepts an arbitrary list and converts it to a heap using Heap queue algorithm.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz


Python: Tips of the Day

Returns every nth element in a list

Example:

def tips_every_nth(lst, nth):
  return lst[nth - 1::nth]

print(tips_every_nth([1, 2, 3, 4, 5, 6, 7, 8, 9], 3))]

Output:

[3, 6, 9]