51

I'm using python2.6. Is it available in higher version of python?
Else is there any other way I can maintain priority queues for list of objects of non-trivial classes? What I need is something like this

>>> l = [ ['a', 3], ['b', 1] ]
>>> def foo(x, y):
...   return x[1]-y[1]
>>> heap = heapify(l, cmp=foo)

Any suggestions ?

Nullpoet
  • 10,949
  • 20
  • 48
  • 65
  • possible duplicate of [How to make heapq evaluate the heap off of a specific attribute?](http://stackoverflow.com/questions/3954530/how-to-make-heapq-evaluate-the-heap-off-of-a-specific-attribute) – Cristian Ciupitu Aug 31 '15 at 02:48

5 Answers5

61

Solution: Wrap data with the new comparison

Since the builtin functions don't directly support cmp functions, we need to build new variants of heapify and heappop:

from heapq import heapify, heappop
from functools import cmp_to_key

def new_heapify(data, cmp):
    s = list(map(cmp_to_key(cmp), data))
    heapify(s)
    return s

def new_heappop(data):
    return heappop(data).obj

Those are used just like your example:

>>> l = [ ['a', 3], ['b', 1] ]
>>> def foo(x, y):
...    return x[1]-y[1]
...
>>> heap = new_heapify(l, cmp=foo)
>>> new_heappop(heap)
['b', 1]

Solution: Store Augmented Tuples

A more traditional solution is to store (priority, task) tuples on the heap:

pq = [ ]
heappush(pq, (10, task1))
heappush(pq, (5, task2))
heappush(pq, (15, task3))
priority, task = heappop(pq)

This works fine as long as no two tasks have the same priority; otherwise, the tasks themselves are compared (which might not work at all in Python 3).

The regular docs give guidance on how to implement priority queues using heapq:

http://docs.python.org/library/heapq.html#priority-queue-implementation-notes

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • 1
    I think it's clear that in this case he wants the priorities to be deduced from the objects rather than manually specified. – agf Oct 21 '11 at 00:17
  • 1
    This also causes trouble when the tasks are `np.array`s, which don't produce booleans upon comparison – Eric Apr 06 '16 at 06:26
  • @Eric Out of curiousity, what would you expect *heapq* to do with an *np.array*? – Raymond Hettinger Nov 15 '19 at 23:30
  • My point was more just to provide another example of when the tasks themselves being incomparable is an issue. I wouldn't expect heapq to work on lists of ndarrays. – Eric Nov 16 '19 at 02:19
  • So is it always true that the first element of the tuple will be used as the key? – information_interchange Apr 19 '20 at 00:46
  • Using id(task) for the second element of the tuple, using the task as the third should prevent the actual tasks from ever being compared. – jpgeek Mar 05 '22 at 10:49
38

Just write an appropriate __lt__ method for the objects in the list so they sort correctly:

class FirstList(list):
    def __lt__(self, other):
        return self[0] < other[0]

lst = [ ['a', 3], ['b', 1] ]

lst = [FirstList(item) for item in lst]

Only __lt__ is needed by Python for sorting, though it's a good idea to define all of the comparisons or use functools.total_ordering.

You can see that it is working by using two items with the same first value and different second values. The two objects will swap places when you heapify no matter what the second values are because lst[0] < lst[1] will always be False. If you need the heapify to be stable, you need a more complex comparison.

agf
  • 171,228
  • 44
  • 289
  • 238
  • 6
    PEP 8 advises that you define all six comparison and not rely on the implementation details of consumer functions. – Raymond Hettinger Oct 20 '11 at 23:24
  • 5
    @RaymondHettinger I know that's the general advice, except in this case it's known which is needed -- the use case isn't arbitrary comparison but for a specific purpose. "it is best to implement all six operations so that confusion doesn't arise in other contexts" doesn't apply if you're only operating in one context. – agf Oct 21 '11 at 00:16
  • 7
    It is trivial to add ``@functools.total_ordering`` to support all six operations effortlessly. FWIW, the PEP 8 advice does apply to the content of working with heaps. The use of \_\_lt\_\_() is an implementation specific detail that is subject to change. Not long ago, it called \_\_le\_\_() instead. – Raymond Hettinger Jun 28 '15 at 00:15
  • 3
    I found that when I started using tuples as in @RaymondHettinger's answer, then I got a significant speedup compared to using an ordering defined for the class. – Joel May 03 '17 at 03:04
6

With these Heap and HeapBy classes I tried to simplify the usage of heapq. You can use HeapBy to pass a key sorting function.

Note that Raymond said that his solution won't work if priorities are repeated and the values are not sortable. That's why I added an example of HeapBy with a NonComparable class.

I took the __lt__ idea from agf's solution.

Usage:

# Use HeapBy with a lambda for sorting
max_heap = HeapBy(key=lambda x: -x)
max_heap.push(3)
max_heap.push(1)
max_heap.push(2)
assert max_heap.pop() == 3
assert max_heap.pop() == 2
assert max_heap.pop() == 1

# Use Heap as a convenience facade for heapq
min_heap = Heap()
min_heap.push(3)
min_heap.push(1)
min_heap.push(2)
assert min_heap.pop() == 1
assert min_heap.pop() == 2
assert min_heap.pop() == 3

# HeapBy also works with non-comparable objects.
# Note that I push a duplicated value
# to make sure heapq will not try to call __lt__ on it.

class NonComparable:
    def __init__(self, val):
        self.val = val

# Using non comparable values
max_heap = HeapBy(key=lambda x: -x.val)
max_heap.push(NonComparable(1))
max_heap.push(NonComparable(1))
max_heap.push(NonComparable(3))
max_heap.push(NonComparable(2))
assert max_heap.pop().val == 3
assert max_heap.pop().val == 2
assert max_heap.pop().val == 1
assert max_heap.pop().val == 1

Classes:

import heapq

class Heap:
    """
    Convenience class for simplifying heapq usage
    """

    def __init__(self, array=None, heapify=True):
        if array:
            self.heap = array
            if heapify:
                heapq.heapify(self.heap)
        else:
            self.heap = []

    def push(self, x):
        heapq.heappush(self.heap, x)

    def pop(self):
        return heapq.heappop(self.heap)


class HeapBy(Heap):
    """
    Heap where you can specify a key function for sorting
    """

    # Item only uses the key function to sort elements,
    # just in case the values are not comparable
    class Item:
        def __init__(self, value, key):
            self.key = key
            self.value = value
        def __lt__(self, other):
            return self.key(self.value) < other.key(other.value)

    def __init__(self, key, array=None, heapify=True):
        super().__init__(array, heapify)
        self.key = key

    def push(self, x):
        super().push(self.Item(x, self.key))

    def pop(self):
        return super().pop().value
Ferran Maylinch
  • 10,919
  • 16
  • 85
  • 100
4

Well, this is terrible and awful and you definitely shouldn't do it… But it looks like the heapq module defines a cmp_lt function, which you could monkey patch if you really wanted a custom compare function.

David Wolever
  • 148,955
  • 89
  • 346
  • 502
  • 1
    Why is it terrible? It works for me! I can even implement max-heap using this approach. – Nullpoet Oct 18 '11 at 06:51
  • 7
    It's terrible and horrible because, unless you're careful, it will break any other code which uses the `heapq` module, and *horribly* break any other code which tries to monkey patch the `heapq` module. Better would be to follow the advice of Raymond Hettinger, the author of a number of Python's modules which implement algorithms like this one. – David Wolever Oct 18 '11 at 17:44
  • Ok, it's horrible, but why doesn't `import heapq` and then `heapq.cmp_lt = lambda x, y: x.value < y.value` work? (in my case I'd compare nodes with values). – Csaba Toth Feb 02 '22 at 08:24
2

I don't know if this is better but it is like Raymond Hettinger's solution but the priority is determined from the object.

Let this be your object and you want to sort by the the x attribute.

class Item:                                 
    def __init__(self, x):
        self.x = x

Then have a function which applies the pairing

def create_pairs(items):
     return map(lambda item: (item.x, item), items)

Then apply the function to the lists as input into heapq.merge

list(heapq.merge(create_pairs([Item(1), Item(3)]), 
                 create_pairs([Item(2), Item(5)])))

Which gave me the following output

[(1, <__main__.Item instance at 0x2660cb0>),
 (2, <__main__.Item instance at 0x26c2830>),
 (3, <__main__.Item instance at 0x26c27e8>),
 (5, <__main__.Item instance at 0x26c2878>)]
Cameron White
  • 542
  • 4
  • 10