Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define heap key for an array of tuples

Tags:

python

heap

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?

like image 771
user1934212 Avatar asked Jul 17 '17 06:07

user1934212


People also ask

How do you use Heapq for tuples in python?

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.

How does heap sort tuple?

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.

Is Heapq a min heap or max heap?

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.


1 Answers

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.

like image 98
Christian Dean Avatar answered Oct 22 '22 22:10

Christian Dean