从heapq python弹出最大值,Python中有最大堆吗?[重复]
发布于 2021-01-29 16:03:00
这个问题已经在这里有了答案 :
7年前关闭。
可能重复:
如何在Python中使用max-heap实现?
我正在尝试以某种方式实现python的heapq,但要实现最大堆。一种解决方案是使用(-1)和带队列号的倍数,但这对我没有帮助,因为我需要将URL存储在堆中。所以我想要一个max
heapq,我可以在其中弹出最大值。
关注者
0
被浏览
157
1 个回答
-
将对象包装在反向比较包装器中:
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