Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python heapq : How do I sort the heap using nth element of the list of lists?

Tags:

python

So I have lists of lists getting added to the heap; eg:

 n = [[1, 5, 93],
     [2, 6, 44],
     [4, 7, 45],
     [6, 3, 12]]

 heapq.heapify(n)
 print(n)

This compares and sorts according to the list's first element.

My question is, how do I sort the heapq so it compares the third element of each list? For example, the above list would be accessed from the heapq in this order:

[[6, 3, 12],
 [2, 6, 44],
 [4, 7, 45],
 [1, 5, 93]]
like image 478
Aditya Pokharel Avatar asked Aug 26 '17 06:08

Aditya Pokharel


People also ask

Is Python Heapq sorted?

The heapq implements a min-heap sort algorithm suitable for use with Python's lists. A heap is a tree-like data structure where the child nodes have a sort-order relationship with the parents.

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.

Is Heapq 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.

Does Heapify sort the list?

heapify function does not give sorted list.


1 Answers

heapq doesn't support a key function for it's ordering so you will need to manipulate your data structure. Mapping your list to a tuple(sort_value, list) will allow you to do log(n) push and pop:

 In []:
 q = [(x[2], x) for x in n]
 heapq.heapify(q)
 heapq.heappop(q)

 Out[]:
 (12, [6, 3, 12])

 In []:
 l = [2, 5, 1]
 heapq.heappush(q, (l[2], l))
 heapq.heappop(q)

 Out[]:
 (1, [2, 5, 1])

Alternatively, define your own list and implement the comparison function for that list:

class MyList(list):
    def __lt__(self, other):
        return self[2] < other[2]

q = [MyList(x) for x in n]

Note: you should implement the other comparison functions (see functools.total_ordering on how to do that easily).

like image 65
AChampion Avatar answered Nov 15 '22 04:11

AChampion