built-in max heap API in Python

前端 未结 2 1914
一向
一向 2021-02-03 22:50

Default heapq is min queue implementation and wondering if there is an option for max queue? Thanks.

I tried the solution using _heapify_max for max heap, but how to han

2条回答
  •  名媛妹妹
    2021-02-03 22:57

    In the past I have simply used sortedcontainers's SortedList for this, as:

    > a = SortedList()
    > a.add(3)
    > a.add(2)
    > a.add(1)
    > a.pop()
    3
    

    It's not a heap, but it's fast and works directly as required.

    If you absolutely need it to be a heap, you could make a general negation class to hold your items.

    class Neg():
        def __init__(self, x):
            self.x = x
    
        def __cmp__(self, other):
            return -cmp(self.x, other.x)
    
    def maxheappush(heap, item):
        heapq.heappush(heap, Neg(item))
    
    def maxheappop(heap):
        return heapq.heappop(heap).x
    

    But that will be using a little more memory.

提交回复
热议问题