Heap
A max heap implementation where the largest element is always at the root.Constructor
Class Methods
from_list(mylist)
Create a heap from a list of elements.The list of elements to be inserted into the heap.
An instance of the heap with all elements from the list inserted.
Methods
raw_view()
Return the heap in its internal array representation.The list representation of the heap.
root()
Get the root value (maximum value in a max heap).The root node’s value, or None if the heap is empty.
peek()
Get the max value of the max heap (same as root()).The maximum value in the heap.
last()
Get the last node of the max heap.The last node’s value, or None if the heap is empty.
left_index(index)
Get the index of the left child node.The index of the parent node.
The index of the left child.
right_index(index)
Get the index of the right child node.The index of the parent node.
The index of the right child.
parent_index(index)
Get the index of the parent node.The index of the child node.
The index of the parent node.
has_left(index)
Check if the current node has a left child.The index of the node.
True if the node has a left child, False otherwise.
has_right(index)
Check if the current node has a right child.The index of the node.
True if the node has a right child, False otherwise.
has_parent(index)
Check if a node has a parent node.The index of the node.
True if the node has a parent, False otherwise.
insert(value)
Insert a value into the heap.The value to insert.
heapify_up(index)
Perform heapify up operation starting at a given index. This maintains the max heap property by moving an element up the tree.The starting index.
pop()
Return the value of the root node (max value) and remove it from the heap.The maximum value from the heap.
Exception: If the heap is empty
heapify_down(index)
Perform heapify down operation starting at a given index. This maintains the max heap property by moving an element down the tree.The starting index.
enumerate()
Return the enumeration of the heap.Enumeration of the heap’s internal array.
count()
Return the number of items in the heap.The number of items in the heap.
is_empty()
Check if the heap has any items.True if the heap has no items, False otherwise.
print()
Print the contents of the heap in level-order.to_sorted_list()
Return a sorted list from the heap (descending order for max heap).A sorted list in descending order.
extract_max()
Return the value of the root node (max value) and remove it from the heap. Alias for pop().The maximum value from the heap.
Special Methods
__repr__()
Return string representation of the heap in order of priority.String showing elements in descending order of priority.
__len__()
Get the number of items in the heap.Number of items in the heap.
__eq__(other)
Compare two Heap objects for value-based equality.The other heap to compare against.
True if both are Heap instances and their internal arrays are equal.