【问题标题】:Unusual result from heappop?heappop的异常结果?
【发布时间】:2016-08-20 23:21:37
【问题描述】:

我有一个简单的堆定义为列表列表。我使用 heapq 模块中的 heapop 来提取具有最小键的列表(我了解到它隐含地是内部列表的第一个元素)。但在以下情况下,pop 操作似乎给出了不寻常的结果。

谁能解释一下原因?

堆=[[0, 0, 0], [inf, 1, 1], [inf, 2, 2], [5, 3, 3], [inf, 4, 4]]

heapq.heappop(堆)

[0, 0, 0]

heapq.heappop(堆)

[inf, 1, 1]

heapq.heappop(堆)

[5, 3, 3]

heapq.heappop(堆)

[inf, 2, 2]

heapq.heappop(堆)

[inf, 4, 4]

【问题讨论】:

    标签: python python-2.7 heap


    【解决方案1】:

    问题是您在不是堆的列表上使用 heapq。 documentation 讨论了使用 heapify 命令,并且确实有效:

    >>> import heapq
    >>> from numpy import inf
    >>> heap=[[0, 0, 0], [inf, 1, 1], [inf, 2, 2], [5, 3, 3], [inf, 4, 4]]
    >>> heapq.heapify(heap)
    >>> heap
    [[0, 0, 0], [5, 3, 3], [inf, 2, 2], [inf, 1, 1], [inf, 4, 4]]
    >>> heapq.heappop(heap)
    [0, 0, 0]
    >>> heapq.heappop(heap)
    [5, 3, 3]
    >>> heapq.heappop(heap)
    [inf, 1, 1]
    >>> heapq.heappop(heap)
    [inf, 2, 2]
    >>> heapq.heappop(heap)
    [inf, 4, 4]
    

    【讨论】:

    • 如果我在执行某些操作时将 inf 修改为某个值怎么办?我需要再次运行 heapify 吗?
    • 如果您可能会更改订单,那么您需要再次 heapify。这不是魔法——它只是一种标准化的排序算法。一种选择是将要更改的列表堆出,然后堆入新列表。如果要将列表保留为堆,则只能使用 heapq 操作对其进行修改
    • heapq.heapreplace 是一个可以让你同时进行 pop 和 push 的函数
    • 查看heapq documentation - 非常好。
    • 我正在实现 Dijkstra 的算法,其中第一个值(表示与源的距离)随着形成更好的路径而被修改。到目前为止,我只是使用列表分配更改值。你有更好的建议吗?
    猜你喜欢
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多