在 Python 中使用什么来实现最大堆?
Python 包含 heapq 模块。 wikipedia.org/wiki/Binary_heap" rel="noreferrer">min-heaps,但我需要一个 最大堆。我应该使用什么来实现 Python 中的最大堆?
Python includes the heapq module for min-heaps, but I need a max-heap. What should I use for a max-heap implementation in Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
最简单的方法是反转键的值并使用 heapq。例如,将 1000.0 变为 -1000.0,将 5.0 变为 -5.0。
The easiest way is to invert the value of the keys and use heapq. For example, turn 1000.0 into -1000.0 and 5.0 into -5.0.
您可以使用
如果您想弹出元素,请使用:
You can use
If you then want to pop elements, use:
解决方案是在将值存储在堆中时对它们取反,或者反转对象比较,如下所示:
最大堆的示例:
但是您必须记住包装和解开您的值,这需要知道您是否正在处理最小或最大堆。
MinHeap、MaxHeap 类
为
MinHeap
和MaxHeap
对象添加类可以简化您的代码:示例用法:
The solution is to negate your values when you store them in the heap, or invert your object comparison like so:
Example of a max-heap:
But you have to remember to wrap and unwrap your values, which requires knowing if you are dealing with a min- or max-heap.
MinHeap, MaxHeap classes
Adding classes for
MinHeap
andMaxHeap
objects can simplify your code:Example usage:
最简单且理想的解决方案
就可以了。所有最高的数字现在都是最低的,反之亦然。
请记住,当您弹出一个元素时,将其乘以 -1 以再次获得原始值。
The easiest and ideal solution
There you go. All the highest numbers are now the lowest and vice versa.
Just remember that when you pop an element to multiply it with -1 in order to get the original value again.
最简单的方法是将每个元素转换为负数,它将解决您的问题。
输出将如下所示:
The easiest way is to convert every element into negative and it will solve your problem.
The output will look like:
我还需要使用最大堆,而且我正在处理整数,所以我只是从
heap
包装了我需要的两个方法,如下所示:然后我刚刚替换了我的
heapq. heappush()
和heapq.heappop()
分别使用heappush()
和heappop()
进行调用。I also needed to use a max-heap, and I was dealing with integers, so I just wrapped the two methods that I needed from
heap
as follows:And then I just replaced my
heapq.heappush()
andheapq.heappop()
calls withheappush()
andheappop()
respectively.我实现了 heapq 的 max-heap 版本并将其提交给 PyPI。 (heapq 模块的 CPython 代码有非常细微的变化。)
heapq_max
Heapq_max (GitHub)
安装
用法
tl;dr: 与 heapq 模块相同,只是在所有函数中添加 '_max'。
I implemented a max-heap version of heapq and submitted it to PyPI. (Very slight change of the heapq module's CPython code.)
heapq_max
Heapq_max (GitHub)
Installation
Usage
tl;dr: The same as the heapq module, except adding ‘_max’ to all functions.
这是一个基于 heapq 的简单最大堆实现。尽管它仅适用于数值。
用法:
This is a simple max-heap implementation based on heapq. Though it only works with numeric values.
Usage:
最简单的方法:
The simplest way:
如果您要插入可比较但不类似 int 的键,则可能会覆盖它们上的比较运算符(即 <= 变为 > 且 > 变为 <=)。否则,您可以覆盖 heapq 模块中的 heapq._siftup (最终,这只是 Python 代码)。
If you are inserting keys that are comparable but not int-like, you could potentially override the comparison operators on them (i.e. <= become > and > becomes <=). Otherwise, you can override heapq._siftup in the heapq module (it's all just Python code, in the end).
扩展 int 类并重写 __lt__ 是方法之一。
Extending the int class and overriding __lt__ is one of the ways.
允许您选择任意数量的最大或最小的项目
Allowing you to chose an arbitrary amount of largest or smallest items
我创建了一个堆包装器,它反转值以创建最大堆,以及最小堆的包装器类,以使库更像 OOP。 这里是要点。共有三个班级; Heap(抽象类)、HeapMin 和 HeapMax。
方法:
I have created a heap wrapper that inverts the values to create a max-heap, as well as a wrapper class for a min-heap to make the library more OOP-like. Here is the gist. There are three classes; Heap (abstract class), HeapMin, and HeapMax.
Methods:
详细说明 Apoorv Patne 的答案,这里是针对一般情况的完整记录、注释和测试的 Python 3 实现。
https://gist.github.com/marccarre/577a55850998da02af3d4b7b98152cf4
To elaborate on Apoorv Patne's answer, here is a fully documented, annotated and tested Python 3 implementation for the general case.
https://gist.github.com/marccarre/577a55850998da02af3d4b7b98152cf4
heapq 模块拥有实现最大堆所需的一切。
它仅执行最大堆的 heappush 功能。
我在下面演示了如何克服这个问题。
在 heapq 模块中添加这个函数:
最后,添加这个:
瞧!完成了。
PS - 转到heapq函数。首先在编辑器中写入“import heapq”,然后右键单击“heapq”并选择“转到定义”。
The heapq module has everything you need to implement a max-heap.
It does only the heappush functionality of a max-heap.
I've demonstrated below how to overcome that.
Add this function in the heapq module:
And at the end, add this:
Voila! It's done.
PS - to go to heapq function. First write "import heapq" in your editor and then right click 'heapq' and select go to definition.
如果您想使用最大堆获得最大的 K 元素,您可以执行以下技巧:
In case if you would like to get the largest K element using max heap, you can do the following trick:
试试这个。
Try this.
Python 中有一个内置堆,但以下是您自己构建它的方法。该算法有效,但我不知道效率如何。
输出
heapify 之前
[5, 7, 0, 8, 9, 10, 20, 30, 50, -1, -2]
heapify 之后
[50, 30, 20, 8, 9, 10, 0, 7, 5, - 1, -2]
排序后
[-2, -1, 0, 5, 7, 8, 9, 10, 20, 30, 50]
There's a built-in heap in Python, but here is how build it by yourself. The algorithm is working, but about the efficiency I don't know.
Output
Before heapify
[5, 7, 0, 8, 9, 10, 20, 30, 50, -1, -2]
After heapify
[50, 30, 20, 8, 9, 10, 0, 7, 5, -1, -2]
After sort
[-2, -1, 0, 5, 7, 8, 9, 10, 20, 30, 50]
我创建了一个名为 heap_class 的包,它实现了 max-heaps,并且还将各种堆函数包装到列表兼容的环境中。
从最大堆中获取最小堆。
正如其他人提到的,由于不同形式的否定,在最大堆中处理字符串和复杂对象在 heapq 中相当困难。使用 heap_class 实现很容易:
支持自定义键并可与后续的推送/追加和弹出一起使用:(
该实现基于 heapq 函数构建,因此全部用 C 语言或 C 包装器编写,除了 max- 上的 heappush 和 heapreplace 之外Python 中的堆。)
I've created a package called heap_class that implements max-heaps, and also wraps the various heap functions into a list-compatible environment.
Get a min-heap from a max-heap.
As others have mentioned, working with strings and complex objects in a max-heap is rather hard in heapq because of the different forms of negation. It is easy with the heap_class implementation:
Custom keys are supported and work with subsequent pushes/appends and pops:
(The implementation is built on heapq functions, so it is all in C or with C-wrappers, except heappush and heapreplace on max-heap which is in Python.)