【问题标题】:Descending order using heapq使用 heapq 降序
【发布时间】:2017-12-01 05:34:54
【问题描述】:

我正在使用 Python 的 heapq 模块按升序和降序获取数据。

对于升序,我使用的是最小堆,它的工作原理如下:

>>> from heapq import heapify, heappop
>>> heap = [9, 3, 1, 5, 6, 2, 7]
>>> heapify(heap)
>>> heappop(heap)
1
>>> heappop(heap)
2
>>> heappop(heap)
3

对于降序,我尝试了以下不同的方法,但它们都有一些缺点:

  1. 使用负值作为优先级进行反向排序。我必须使用单独的列表来使数据可重用。如果原始列表很大,则拥有列表副本的成本很高。

    >>> from heapq import heapify, heappop
    >>> heap = [9, 3, 1, 5, 6, 2, 7]
    >>> heap_neg = [-x for x in heap]
    >>> heapify(heap_neg)
    >>> -heappop(heap_neg)
    9
    >>> -heappop(heap_neg)
    7
    >>> -heappop(heap_neg)
    6
    
  2. 优先使用负值的元组,这样也很浪费空间。我不想将整数列表存储为元组列表。

    >>> from heapq import heapify, heappop
    >>> heap = [(-9, 9), (-3, 3), (-1, 1), (-5, 5), (-6, 6), (-2,2), (-7,7)]
    >>> heapify(heap)
    >>> heappop(heap)[1]
    9
    >>> heappop(heap)[1]
    7
    >>> heappop(heap)[1]
    6
    
  3. 在 heapify 中使用 key 排序丢失。比如:

    >>> from heapq import heapify, heappop
    >>> heap = [9, 3, 1, 5, 6, 2, 7]
    >>> heapify(heap, key=lambda x:-x) # This doesn't work as heapify don't have key parameter
    
  4. 如果我使用 heapq._heapify_max(heap),我将不得不在每个元素弹出后 _heapify_max。喜欢:

    >>> from heapq import _heapify_max, heappop
    >>> heap = [9, 3, 1, 5, 6, 2, 7]
    >>> _heapify_max(heap)
    >>> heappop(heap)
    9
    >>> heappop(heap)  # popping without _heapify_max gives wrong result
    1
    >>> _heapify_max(heap)
    >>> heappop(heap) # popping after _heapify_max gives correct result
    7
    

有什么方法可以让我获得 descending 订单类似于我获得 ascending 订单的方式吗? :)

【问题讨论】:

  • 如果您只需要特定数量的最大元素,您可以尝试heapq.nlargest(还有heapq.nsmallest 可以完成您的第一组代码所做的工作)。当您关心的项目数远小于原始列表中的项目数时,这非常有效。
  • 既然您愿意使用heapq 的未记录的max 功能,那么在您_heapify_max(heap) 之后会有一个_heappop_max(heap)。
  • 你能显示你的运行中位数代码吗?当您在数据流上计算结果时,我不确定您对在否定值情况下复制数据的担忧如何适用。在这种情况下,你肯定会从两个空堆开始,不是吗?
  • @AChampion:可惜没有_heappush_max,所以使用未记录的函数也是不完善的。
  • 该代码不起作用,因为您从不在其上调用_heapify_max。您需要在开始时 heapify 一次,否则它不会具有 heap 属性,并且其他操作不会执行您想要的操作。只需一次调用(在第一次弹出之前),您就会得到预期的结果。

标签: python python-2.7 python-3.x heap


【解决方案1】:

正如我们在 cmets 中所讨论的,当您从空堆开始并随时添加值时,您对使用否定值将最小堆翻转为最大堆时复制数据的担忧并不重要.由于这是查找值流的运行中位数时的用例,因此在添加值时取反应该可以正常工作。

这是我写的一个正在运行的中值生成器,只是为了仔细检查它是否按我预期的方式工作:

def running_median(iterable):
    left_q = [] # heap of smaller-than-median elements, stored negated
    right_q = [] # heap of larger-than-median elements

    for value in iterable:
        if len(left_q) == len(right_q): # push to left_q when they're equal size
            if len(right_q) > 0 and value > right_q[0]:
                value = heapq.heapreplace(right_q, value)
            heapq.heappush(left_q, -value)
        else: # push to right_q only when it's (strictly) smaller
            if value < -left_q[0]:
                value = -heapq.heapreplace(left_q, -value)
            heapq.heappush(right_q, value)

        # len(left_q) is always >= len(right_q) so we never yield right_q[0]
        if len(left_q) > len(right_q):
            yield -left_q[0]
        else:
            yield (-left_q[0] + right_q[0]) / 2

left_q 堆存储小于或等于中值的值。每个值在被推送时都会被否定,因此对其使用正常的最小堆操作使其像最大堆一样工作。我们只需要记住重新否定我们从中取出的任何值,以恢复原始符号。

【讨论】:

    【解决方案2】:

    在这种情况下,我认为您正在寻找一个排序的链表,我修改了我找到的人 here,所以它会按升序插入(我添加了 pop 函数,由于某种原因它不在代码中,但我认为您可能需要它):

    # Python program to insert in sorted list
    
    # Node class 
    class Node:
    
        # Constructor to initialize the node object
        def __init__(self, data):
            self.data = data
            self.next = None
    
    class LinkedList:
    
        # Function to initialize head
        def __init__(self):
            self.head = None
    
        def sortedInsert(self, new_node):
    
            # Special case for the empty linked list 
            if self.head is None:
                new_node.next = self.head
                self.head = new_node
    
            # Special case for head at end
            elif self.head.data <= new_node.data:
                new_node.next = self.head
                self.head = new_node
    
            else :
    
                # Locate the node before the point of insertion
                current = self.head
                while(current.next is not None and
                     current.next.data > new_node.data):
                    current = current.next
    
                new_node.next = current.next
                current.next = new_node
    
        # Function to insert a new node at the beginning
        def push(self, new_data):
            new_node = Node(new_data)
            new_node.next = self.head
            self.head = new_node
    
        # Utility function to prit the linked LinkedList
        def printList(self):
            temp = self.head
            while(temp):
                print(temp.data),
                temp = temp.next
    
        def pop(self):
            val = self.head.data
            self.head = self.head.next
            return val
    
    
    # Driver program
    llist = LinkedList()
    new_node = Node(5)
    llist.sortedInsert(new_node)
    new_node = Node(10)
    llist.sortedInsert(new_node)
    new_node = Node(7)
    llist.sortedInsert(new_node)
    new_node = Node(3)
    llist.sortedInsert(new_node)
    new_node = Node(1)
    llist.sortedInsert(new_node)
    new_node = Node(9)
    llist.sortedInsert(new_node)
    print("Create Linked List")
    llist.printList()
    

    如您所见,只需将 >= 更改为

    【讨论】:

    • 非常感谢 Damian 的回答,但我想使用一些内置的。另外,我想使用堆,因为与使用链表的 O(n) 相比,插入的复杂度为 O(logn)。
    • @rishap 你想过在树上吗?准确地说是orderedtreeset?这里有一些文档knuth.luther.edu/~leekent/CS2Plus/chap6/chap6.html
    【解决方案3】:

    有这方面的私有方法(在 python 3.8 测试)

    import heapq
    
    
    if __name__ == '__main__':
        a = [1, 3, 2, 5]
    
        heapq._heapify_max(a)
    
        for item in range(0, len(a)):
            print(heapq._heappop_max(a)
    

    结果是

    sorted heap  5
    sorted heap  3
    sorted heap  2
    sorted heap  1
    

    但是对于某些人来说,使用私有方法可能看起来不够正确。出于这个原因,我们可以通过将您的对象放在修改后的包装器中来更改顺序

    class DescOrder:
        def __init__(self, entity):
            self.entity = entity
    
        def __lt__(self, o):
            return self.entity.__gt__(o.entity)
    
        def __repr__(self):
            return str(self.entity)
    
    def check_sorting(a, b):
        new_heap = []
    
        for element in a:
            heapq.heappush(new_heap, DescOrder(element))
    
        for index in range(0, len(b)):
            assert heapq.heappop(new_heap).entity == b[index]
    
    
    if __name__ == '__main__':
        check_sorting([5, 1, -1, 3, 2], [5, 3, 2, 1, -1])
        check_sorting([5, 2, -1, 3, 1], [5, 3, 2, 1, -1])
        check_sorting([-1, 2, 5, 3, 1], [5, 3, 2, 1, -1])
     
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-29
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      • 2019-05-01
      • 2018-07-18
      相关资源
      最近更新 更多