来自heapq python的pop max值,Python中是否有最大堆?

时间:2012-10-01 22:04:10

标签: python min-heap max-heap

  

可能重复:
  What do I use for a max-heap implementation in Python?

我试图以某种方式实现python的heapq但是对于max-heap。一个解决方案是使用(-1)和多个队列号,但这对我没有帮助,因为我需要将URL存储在堆中。所以我想要一个max heapq,我可以弹出最大值。

1 个答案:

答案 0 :(得分:8)

将对象包装在反向比较包装器中:

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)

用法:

import heapq
letters = 'axuebizjmf'
heap = map(ReverseCompare, letters)
heapq.heapify(heap)
print heapq.heappop(heap) # prints z