A generic Heap class, can be used as min or max by passing the key function |
|
A generic Heap class, can be used as min or max by passing the key function accordingly.
Compares the two items using default comparison
Returns index of valid parent as per desired ordering among given index and both it’s children
Fixes the heap in downward direction of given index
Fixes the heap in upward direction of given index
Returns left-child-index of given index if exists else None
Returns parent index of given index if exists else None
Returns right-child-index of given index if exists else None
Performs changes required for swapping two elements in the heap
Deletes given item from heap if present
Return top item tuple (Calculated value, item) from heap and removes it as well if present
Returns top item tuple (Calculated value, item) from heap if present
Inserts given item with given value in heap
Updates given item value in heap if present
>>> h = Heap() # Max-heap
>>> h.insert_item(5, 34)
>>> h.insert_item(6, 31)
>>> h.insert_item(7, 37)
>>> h.get_top()
[7, 37]
>>> h.extract_top()
[7, 37]
>>> h.extract_top()
[5, 34]
>>> h.extract_top()
[6, 31]
>>> h = Heap(key=lambda x: -x) # Min heap
>>> h.insert_item(5, 34)
>>> h.insert_item(6, 31)
>>> h.insert_item(7, 37)
>>> h.get_top()
[6, -31]
>>> h.extract_top()
[6, -31]
>>> h.extract_top()
[5, -34]
>>> h.extract_top()
[7, -37]
>>> h.insert_item(8, 45)
>>> h.insert_item(9, 40)
>>> h.insert_item(10, 50)
>>> h.get_top()
[9, -40]
>>> h.update_item(10, 30)
>>> h.get_top()
[10, -30]
>>> h.delete_item(10)
>>> h.get_top()
[9, -40]