Python Heap Queue Algorithm


The heap data structures can be used to represents a priority queue. In python it is available into the heapq module. Here it creates a min-heap. So when the priority is 1, it represents the highest priority. When new elements are inserted, the heap structure updates.

To use this module, we should import it using −

import heapq

There are some heap related operations. These are −

Method heapq.heapify(iterable)

It is used to convert an iterable dataset to heap data structure.

Method heapq.heappush(heap, element)

This method is used to insert the element into the heap. After that re-heap the entire heap structure.

Method heapq.heappop(heap)

This method is used to return and delete the element from the top of the heap and perform heapify on the rest of the elements.

Method heapq.heappushpop(heap, element)

This method is used to insert and pop element in one statement..

Method heapq.heapreplace(heap, element)

This method is used to insert and pop element in one statement. It removes the element from root of the heap, then insert element into the heap.

Method heapq.nlargest(n, iterable, key=None)

This method is used to return n largest element from the heap.

Method heapq.nsmallest(n, iterable, key=None)

This method is used to return n smallest element from the heap.

Example Code

Live Demo

import heapq
my_list = [58, 41, 12, 17, 89, 65, 23, 20, 10, 16, 17, 19]
heapq.heapify(my_list)
print(my_list)
heapq.heappush(my_list, 7)
print(my_list)
print('Popped Element: ' + str(heapq.heappop(my_list)))
print(my_list)
new_iter = list()
new_iter = heapq.nlargest(4, my_list)
print(new_iter)

Output

[10, 16, 12, 17, 17, 19, 23, 20, 41, 89, 58, 65]
[7, 16, 10, 17, 17, 12, 23, 20, 41, 89, 58, 65, 19]
Popped Element: 7
[10, 16, 12, 17, 17, 19, 23, 20, 41, 89, 58, 65]
[89, 65, 58, 41]

Updated on: 30-Jul-2019

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements