可能的重复:
在 Python 中使用什么来实现最大堆?
我正在尝试以某种方式实现 python 的 heapq 但对于最大堆。解决方案是使用 (-1) 和多个队列编号,但这对我没有帮助,因为我需要在堆中存储 url。所以我想要一个最大堆,我可以在其中弹出最大值。
将对象包装在反向比较包装器中:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)