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

别说谁变了你拦得住时间么 提交于 2019-11-30 16:28:07

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