def setUp(self): self.min_heap = BinaryHeap() self.min_heap.insert(4) self.min_heap.insert(50) self.min_heap.insert(7) self.min_heap.insert(55) self.min_heap.insert(90) self.min_heap.insert(87)
def setUp(self): self.min_heap = BinaryHeap() self.min_heap.insert(4) self.min_heap.insert(50) self.min_heap.insert(7) self.min_heap.insert(55) self.min_heap.insert(90) self.min_heap.insert(87)
def dijkstra_min_heap(self, src): """ Dijkstra's using a priority queue, more specifically a Binary heap. Time complexity: O((|E| + |V|)logV) """ if self.vertices == 0: return [] heap = BinaryHeap() dist = [float("inf")] * self.vertices tuple = (0, src) heap.insert(tuple) dist[src] = 0 while heap.currentSize > 0: u = heap.remove_min() curWeight = u[0] curNode = u[1] # go over all vertices adjacent to u for v in range(self.vertices): if (self.graph[curNode][v] > 0 and dist[v] > dist[curNode] + self.graph[curNode][v]): dist[v] = dist[curNode] + self.graph[curNode][v] heap.insert((dist[v], v)) return dist
class TestBinaryHeap(unittest.TestCase): """ Test suite for the binary_heap data structures """ def setUp(self): self.min_heap = BinaryHeap() self.min_heap.insert(4) self.min_heap.insert(50) self.min_heap.insert(7) self.min_heap.insert(55) self.min_heap.insert(90) self.min_heap.insert(87) def test_insert(self): # Before insert 2: [0, 4, 50, 7, 55, 90, 87] # After insert: [0, 2, 50, 4, 55, 90, 87, 7] self.min_heap.insert(2) self.assertEqual([0, 2, 50, 4, 55, 90, 87, 7], self.min_heap.heap) self.assertEqual(7, self.min_heap.currentSize) def test_remove_min(self): ret = self.min_heap.remove_min() # Before remove_min : [0, 4, 50, 7, 55, 90, 87] # After remove_min: [7, 50, 87, 55, 90] # Test return value self.assertEqual(4, ret) self.assertEqual([0, 7, 50, 87, 55, 90], self.min_heap.heap) self.assertEqual(5, self.min_heap.currentSize)
class TestBinaryHeap(unittest.TestCase): """ Test suite for the binary_heap data structures """ def setUp(self): self.min_heap = BinaryHeap() self.min_heap.insert(4) self.min_heap.insert(50) self.min_heap.insert(7) self.min_heap.insert(55) self.min_heap.insert(90) self.min_heap.insert(87) def test_insert(self): # Before insert 2: [0, 4, 50, 7, 55, 90, 87] # After insert: [0, 2, 50, 4, 55, 90, 87, 7] self.min_heap.insert(2) self.assertEqual([0, 2, 50, 4, 55, 90, 87, 7], self.min_heap.heap) self.assertEqual(7, self.min_heap.currentSize) def test_remove_min(self): ret = self.min_heap.remove_min() # Before remove_min : [0, 4, 50, 7, 55, 90, 87] # After remove_min: [7, 50, 87, 55, 90] # Test return value self.assertEqual(4,ret) self.assertEqual([0, 7, 50, 87, 55, 90], self.min_heap.heap) self.assertEqual(5, self.min_heap.currentSize)