What do I use for a max-heap implementation in Python?

Douglas Mayle picture Douglas Mayle · Mar 23, 2010 · Viewed 139.4k times · Source

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?

Answer

Daniel Stutzbach picture Daniel Stutzbach · Mar 23, 2010

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.