""" heap.py a miminal implementation of a priority queue as a binary heap including heapsort See https://runestone.academy/runestone/books/published/pythonds/Trees/BinaryHeapImplementation.html We'll do at least these operations. - create - add an element - remve an element The heap stores these indeces 0 1 2 3 4 5 6 as these places in a binary tree 0 1 2 3 4 5 6 and we can find the index of parents and children with these formulas. left_child 2*i + 1 (for parent at i) right_child 2*i + 2 parent (n-1)//2 (for child at n) check : (5 - 1) // 2 => 2 (6 - 1) // 2 = 5 //2 = round_down(2.5) => 2 """ def parent(i): """ return the index of the parent of node with index i >>> parent(5) 2 >>> parent(6) 2 """ # Remember that // is the "integer division" operator in python. return (i-1) // 2 def left_child(i): """ return index of the left child of the node with index i """ return 2*i + 1 def right_child(i): """ return index of the left child of the node with index i """ return 2*i + 2 class Heap: def __init__(self): self.array = [] def set_test_case(self): # a valid heap that we can play with; # same numbers as in the pythonds material. # 5 # 9 11 # 14 18 self.array = [5, 9, 11, 14, 18] def main(): heap = Heap() heap.set_test_case() if __name__ == "__main__": import doctest doctest.testmod() main()