A simple example for the usage of the python heap implementation is
from heapq import heappush, heappop
heap = []
data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
for item in data:
heappush(heap, item)
In a more complicated scenario, I have an array of tuples like
tuples = [(5,"foo",True),(2,"bar", False),(8,"foobar",True)]
and want to use the first entry of each tuple as heap key, i.e. the tuples should be sorted according to the number in the tuples.
How can I do that?
The heapq module functions can take either a list of items or a list of tuples as a parameter. Thus, there are two ways to customize the sorting process: Convert the iterable to a list of tuples/list for comparison. Write a wrapper class that overrides '<' operator.
heap of the tuple will first sort base on the first element of the tuple, of the first element is equal, then compare the second element.
The heapq module of python implements the heap queue algorithm. It uses the min heap where the key of the parent is less than or equal to those of its children.
You can simply use the tuple as they are. The Python documentation explicitly makes note of such as usage:
Heap elements can be tuples. This is useful for assigning comparison values (such as task priorities) alongside the main record being tracked:
>>> h = [] >>> heappush(h, (5, 'write code')) >>> heappush(h, (7, 'release product')) >>> heappush(h, (1, 'write spec')) >>> heappush(h, (3, 'create tests')) >>> heappop(h) (1, 'write spec')
Simply push the tuples to the heap, and pop them off when needed:
>>> from heapq import heappush, heappop
>>>
>>> heap = []
>>> tuples = [(5,"foo",True),(2,"bar", False),(8,"foobar",True)]
>>>
>>> for tup in tuples:
... heappush(heap, tup)
...
>>> heappop(heap)
(2, 'bar', False)
Because the implementation for heap
uses default sorting for tuples
while pos > startpos:
...
if newitem < parent:
...
...
...
and Python sorts tuples element-wise, ensure the objects by which you want the tuples to be sorted come first.
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