I'm using the heapq
module to determine the smallest item in a list.
I have this below code, but the heapq.heapify()
return value is None.
How do I get the result in a new list?
>>> a=heapq.heapify(lista)
>>> a
>>> lista=[1,2,3,4,5]
>>> a=heapq.heapify(lista)
>>> print(a)
None
Heap queue is a special tree structure in which each parent node is less than or equal to its child node. In python it is implemented using the heapq module. It is very useful is implementing priority queues where the queue item with higher weight is given more priority in processing.
The heapq module is an inbuilt module in Python that offers APIs for different operations of the heap data structure. The module provides min-heap implementation where the key of the parent is less than or equal to those of its children.
The Python heapq module is part of the standard library. It implements all the low-level heap operations as well as some high-level common uses for heaps. A priority queue is a powerful tool that can solve problems as varied as writing an email scheduler, finding the shortest path on a map, or merging log files.
Conclusion: It is clear from the time profiling that, heapq runs faster than PriorityQueue function. And this is obvious because PriorityQueue uses the threading module to implement a mutex structure for thread safety while manipulating items in the queue.
heapq.heapify
doesn't return anything, it heapifies the list in place; it's far more efficient to do it that way:
>>> import heapq
>>> lista = [44, 42, 3, 89, 10]
>>> heapq.heapify(lista)
>>> lista
[3, 10, 44, 89, 42]
If you need a new list, create a copy first:
>>> lista = [44, 42, 3, 89, 10]
>>> newlist = lista[:]
>>> heapq.heapify(newlist)
>>> lista
[44, 42, 3, 89, 10]
>>> newlist
[3, 10, 44, 89, 42]
That defeats the purpose somewhat, of course, as copying the list has a (linear) cost too.
If all you need is the smallest item in a list, the min()
function will be just as fast when locating just the one smallest element (both heapify()
and min()
scan the input list once, so O(n) cost):
>>> min(lista)
3
If you need more than one smallest value, by all means use a heapq
, especially if you add items later on. If you cannot alter the original list, need several smallest items, see looking for an inverted heap in python for an efficient nsmallest
implementation that creates a new heap from an input heap with only a fixed number of smallest values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With