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.
Answer from Daniel Stutzbach on Stack OverflowThe 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
import heapq
listForTree = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
heapq.heapify(listForTree) # for a min heap
heapq._heapify_max(listForTree) # for a maxheap!!
If you then want to pop elements, use:
heapq.heappop(minheap) # pop from minheap
heapq._heappop_max(maxheap) # pop from maxheap
How to use Python's heapq as min-heap AND max-heap?
Make max heap functions public in heapq - Ideas - Discussions on Python.org
Create new package similar to `heapq` but be able to pass custom comparator through a constructor - Ideas - Discussions on Python.org
What do I use for a max-heap implementation in Python?
Videos
I know that heapq in python is min-heap (first element is the smallest).
How do I initialize a max-heap, where the root is the largest?
I am working through grokking the coding interview and decided to use python due to it's readability and overall simplicity in its syntax.
This morning I started working on the 'two heaps' algorithms. It struck me as a bit odd that python or the writers of the heapq library decided to make all implementations of heap minheaps rather than adding some additional APIs for maxheaps.
Maybe it's just me, but I find it a bit hard to reason through programs that make use of maxheaps. Having to remember to push a value multiplied by -1 and then do the same for retrieval feels a bit un-intuitive, but maybe it's just me.
Does anyone know of the reasoning behind not implementing them separately and adding a thin layer to the maxheaps to avoid having to do this? I'm mostly just curious if there was any discussion around it when heapq was created but haven't been able to find anything yet.