Possible Duplicate:
What do I use for a max-heap implementation in Python?
I am trying to implement in some way the heapq of python but for a max-heap. A solution is using the (-1) and multiple with numbers of the queue but that doesn't help me as I need to store urls in the heap. So i want a max heapq where i can pop the largest value.
Wrap the objects in a reverse-comparing wrapper:
import functools
@functools.total_ordering
class ReverseCompare(object):
def __init__(self, obj):
self.obj = obj
def __eq__(self, other):
return isinstance(other, ReverseCompare) and self.obj == other.obj
def __le__(self, other):
return isinstance(other, ReverseCompare) and self.obj >= other.obj
def __str__(self):
return str(self.obj)
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.obj)
Usage:
import heapq
letters = 'axuebizjmf'
heap = map(ReverseCompare, letters)
heapq.heapify(heap)
print heapq.heappop(heap) # prints z
来源:https://stackoverflow.com/questions/12681772/pop-max-value-from-a-heapq-python-is-there-a-max-heap-in-python