class BinHeap: def __init__(self, a_list=[]): """Constructs a BinHeap object. Can either create an empty BinHeap or can construct it from a_list. """ self.heap_list = [0] + a_list for i in range(self.size() // 2, 0, -1): self.perc_down(i) def size(self): """Return the size of the heap.""" return len(self.heap_list) - 1 def perc_up(self, i): """Percolate element i up the heap to its correct position.""" while i // 2 > 0 and self.heap_list[i] < self.heap_list[i // 2]: self.heap_list[i], self.heap_list[i // 2] = \ self.heap_list[i // 2], self.heap_list[i] i = i // 2 def insert(self, k): """Insert k into the heap.""" self.heap_list.append(k) self.perc_up(self.size()) def perc_down(self, i): """Percolate element i down the heap to its correct position.""" while (i * 2) <= self.size(): child = self.min_child(i) if self.heap_list[i] > self.heap_list[child]: self.heap_list[child], self.heap_list[i] = \ self.heap_list[i], self.heap_list[child] i = child def min_child(self, i): """Return the index of the minimum child of index i.""" left = i * 2 right = left + 1 if right > self.size(): return left return left if self.heap_list[left] < self.heap_list[right] else right def del_min(self): """Extract and return the minimum value from the heap.""" ret_val = self.heap_list[1] replacement = self.heap_list.pop() if self.size() > 0: self.heap_list[1] = replacement self.perc_down(1) return ret_val def __str__(self): """Return the readable string of the heap.""" return str(self.heap_list[1:]) # We make the heap in two different ways # and compare the output. bh = BinHeap() print(bh) bh.insert(9) bh.insert(6) bh.insert(5) bh.insert(2) bh.insert(3) print(bh) while bh.size() > 0: print(bh.del_min()) print(bh) bh = BinHeap([9,6,5,2,3]) print(bh) while bh.size() > 0: print(bh.del_min()) print(bh)