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 ?
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:
Those are used just like your example:
Solution: Store Augmented Tuples
A more traditional solution is to store (priority, task) tuples on the heap:
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