What is the Heapq module in Python

What am I using for a max heap implementation in Python?


The easiest way is to invert the value of the keys and use heapq. For example, change 1000.0 to -1000.0 and 5.0 to -5.0.

You can use

Then when you want to insert elements use:

The solution is to negate your values ​​when you store them in the heap or reverse your object comparison like this:

Example of a max heap:

However, you need to remember to package and unpack your values. To do this, you need to know whether it is a min or max heap.

MinHeap, MaxHeap classes

Adding classes for and objects can simplify your code:

Application example:

The simplest and ideal solution

Multiply the values ​​by -1

Here we go. All the highest numbers are now the lowest and vice versa.

Keep this in mind whenever you burst an element to multiply it by -1 to get back its original value.

I implemented a max heap version of Heapq and sent it to PyPI. (Very minor change to the Heapq module's CPython code.)





tl; dr: Same as the Heapq module, except that '_max' is added to all functions.

If you include keys that are comparable but not int-like, you may be able to override the comparison operators (that is, <= will> and> will <=). Otherwise, you can override heapq._siftup in the heapq module (in the end, it's all just python code).

You can choose any number of the largest or smallest elements

Extending the int class and overriding the __lt__ is one of the options.

I 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.


If you want to get the largest K element with max heap, you can do the following trick:

Following Isaac Turner's excellent answer, I'd like to set an example based on K Closest Points to the Origin using Max Heap.

To explain https://stackoverflow.com/a/59311063/1328979, here is a fully documented, commented, and tested Python 3 implementation for the general case.