def TestSizeReducedAfterExtractMin(self): input = [6, 1, 4, 5, 3, 2] h = Heap() for num in input: h.insert(num) initial_size = h.size self.assertEqual(initial_size, len(h.a)) h.extract_min() self.assertEqual(initial_size - 1, h.size)
def TestBuildMinHeap(self): input = [random.randrange(100) for _ in range(100)] h = Heap(input) sorted_input = sorted(input) for i in range(len(input)): self.assertEqual(h.peek_min(), sorted_input[i]) self.assertEqual(h.extract_min(), sorted_input[i])
def TestMinHeapWithTuples(self): input = [(random.randrange(100), "Hullo!") for _ in range(100)] h = Heap(key=lambda x: x[0]) for num in input: h.insert(num) sorted_input = sorted(input) for i in range(len(input)): self.assertEqual(h.extract_min(), sorted_input[i])
def TestMinHeapWithRandomInput(self): input = [random.randrange(100) for _ in range(100)] h = Heap() for num in input: h.insert(num) sorted_input = sorted(input) for i in range(len(input)): self.assertEqual(h.extract_min(), sorted_input[i])
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 TestMinHeapProperty(self): input = [6, 1, 4, 5, 3, 2] h = Heap() for num in input: h.insert(num) self.assertEqual(h.extract_min(), 1)