Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I use for a max-heap implementation in 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?

like image 762
Douglas Mayle Avatar asked Mar 23 '10 15:03

Douglas Mayle


People also ask

How is max heap implemented?

To heapify an element in a max heap we need to find the maximum of its children and swap it with the current element. We continue this process until the heap property is satisfied at each node. In order to heapify we move down from the root to the leaves.

How are heaps implemented in Python?

In the heap data structure, we assign key-value or weight to every node of the tree. Now, the root node key value is compared with the children's nodes and then the tree is arranged accordingly into two categories i.e., max-heap and min-heap.

How do I add heap to Python?

To add a new element to the heap, you append it to the end of the array and then call swim repeatedly until the new element finds its place in the heap. To delete the root, you swap it with the last element in the array, delete it and then call sink until the swapped element finds its place.

Is Python Heapq a min or max heap?

The heapq module of python implements the heap queue algorithm. It uses the min heap where the key of the parent is less than or equal to those of its children.


2 Answers

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.

like image 80
Daniel Stutzbach Avatar answered Sep 20 '22 16:09

Daniel Stutzbach


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 
like image 22
Lijo Joseph Avatar answered Sep 16 '22 16:09

Lijo Joseph