Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make heapq evaluate the heap off of a specific attribute?

I wish to hold a heap of objects, not just numbers. They will have an integer attribute in them that the heap can sort by. The easiest way to use heaps in python is heapq, but how do I tell it to sort by a specific attribute when using heapq?

like image 930
coffee Avatar asked Oct 17 '10 18:10

coffee


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.

Is Heapq min heap or Max?

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.

Is Heapq a binary heap?

This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. Heaps are binary trees for which every parent node has a value less than or equal to any of its children.

What does Heapq Heappop do?

heappush – This function adds an element to the heap without altering the current heap. heappop – This function returns the smallest data element from the heap.


2 Answers

According to the example from the documentation, you can use tuples, and it will sort by the first element of the tuple:

>>> 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') 

So if you don't want to (or can't?) do a __cmp__ method, you can manually extract your sorting key at push time.

Note that if the first elements in a pair of tuples are equal, further elements will be compared. If this is not what you want, you need to ensure that each first element is unique.

like image 180
Jander Avatar answered Sep 22 '22 07:09

Jander


heapq sorts objects the same way list.sort does, so just define a method __cmp__() within your class definition, which will compare itself to another instance of the same class:

def __cmp__(self, other):     return cmp(self.intAttribute, other.intAttribute) 

Works in Python 2.x.

In 3.x use:

def __lt__(self, other):     return self.intAttribute < other.intAttribute 
like image 43
eumiro Avatar answered Sep 18 '22 07:09

eumiro