Pop max value from a heapq python, Is there a max-heap in Python? [duplicate]

走远了吗. 提交于 2019-11-29 23:34:10

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!