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 Overflowdata structures - What do I use for a max-heap implementation in Python? - Stack Overflow
python - What is the difference between heappop and pop(0) on a sorted list? - Stack Overflow
Complexity analysis of heappush, heappop and heapify in Python.
How does heap pop works when popping tuple items?
Videos
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
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
What is the time complexity for these?
I've saw that when setting tuple item as heap element, it would get the first value while popping minimum values from heap.
heap = [(1, 10), (2, 99)]
For the above heap, it's obvious that it would pop the element (1, 10) first, since first elemnt of tuple 1 < 2
However, for those tuple elements where first element is same
heap = [(1, 10), (1, 99)]
I've tested some cases, heap would drop the element (1, 10) first, looks like it compares the second element when first element is same for multiples.
Is that the correct logic that heap would compare following values while first element is the same for tuples?
Yes, you can make this assumption, because it is stated in the documentation:
Heaps are arrays for which
heap[k] <= heap[2*k+1]andheap[k] <= heap[2*k+2]for all k, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is thatheap[0]is always its smallest element.
(And that's probably the reason there is no peek function: there is no need for it.)
If you're using Python 2.4 or newer, you can also use heapq.nsmallest().