def test_heap_invariant(self): heap = MinHeap([2,4,6,8,10,1,3,5,7,9]) for k in range(len(heap)): if 2*k+1 < len(heap): self.assertTrue(heap.get(k) <= heap.get(2*k+1)) if 2*k+2 < len(heap): self.assertTrue(heap.get(k) <= heap.get(2*k+2))
def find_k_largest(a, k): h = MinHeap() for i in range(len(a)): if i < k: h.push(a[i]) elif a[i] > h.peek(): h.pop() h.push(a[i]) return h.getItems()
def full_min_heap(): test_heap = MinHeap() test_heap.add(4) test_heap.add(6) test_heap.add(3) test_heap.add(7) test_heap.add(5) return test_heap
def prim(G, s): """ Implementation of Prims to find MST """ for v in G.V: v.rank = sys.maxsize v.p = None s.rank = 0 Q = MinHeap(G.V) while Q.size() > 0: u = Q.extract_min() for v, weigth in G.adj(u): if v in Q and weigth < v.rank: # updates the predecessor and rank such that we are getting spanning tree with lowest total edge weight v.p = u v.rank = weigth # update heap since ranks have changed Q.build_min_heap() # find all the edges that spans the tree result = [] total_weight = 0 for u in G.V: for v, weigth in G.adj(u): if v.p == u and (u, v, weigth) not in result: result.append((u, v, weigth)) total_weight += weigth print(result, "Minimal weight:", total_weight)
def heapsort(a): a = list(a) heap = MinHeap() heap.heapify(a) a_sorted = [] while heap.peek(): a_sorted.append(heap.extract_min()) return a_sorted
def calculate_medians_with_heaps(numbers): """Calculate the sum of all 10,000 medians, modulo 10000""" max_heap = MaxHeap() # For storing the smaller half of numbers min_heap = MinHeap() # For storing the larger half of numbers medians = [] for number in numbers: if max_heap.peek_max() is None or max_heap.peek_max() > number: max_heap.insert(number) if max_heap.size > min_heap.size + 1: min_heap.insert(max_heap.extract_max()) else: min_heap.insert(number) if min_heap.size > max_heap.size + 1: max_heap.insert(min_heap.extract_min()) if max_heap.size >= min_heap.size: medians.append(max_heap.peek_max()) else: medians.append(min_heap.peek_min()) return medians
def test_it_can_make_heaps(self): minHeap = MinHeap() self.assertIsInstance(minHeap, MinHeap) maxHeap = MaxHeap() self.assertIsInstance(maxHeap, MaxHeap)
def test_min_heap_has_min_at_top(self): minHeap = MinHeap() minHeap.push(10) minHeap.push(1) self.assertEqual(minHeap.peek(), 1)
def test_initialize(self): heap = MinHeap([2,4,6,8,10,1,3,5,7,9]) self.assertEquals(heap.get(0), 1)
from heaps import MinHeap from heaps import random lst = [] heap = MinHeap() for i in range(10): random_number = random.randint(1, 10) lst.append(random_number) for i in lst: heap.add(i) print(heap.heap_list) print(heap.traverse(5))
def init_min_heap(): test_heap = MinHeap() return test_heap