def test_push(): u"""Assert that the heap has correct head through multiple pushes.""" heap = Heap() numsPushed = [] for num in NUMBERS: heap.push(num) numsPushed.append(num) assert heap[0] == max(numsPushed)
def print_sorted(result): heap = Heap() for key in result: heap.add(sum(result[key]), str(result[key]) + ' ' + key) sorted_result = heap.sort() i = 0 for item in sorted_result: i += 1 print(str(i) + '. ' + str(item[0]) + ' ' + item[1])
def testExtractMax(self): # Single element heap = Heap([1]) assert heap.extract_max() == 1 # Sorted, n = 2 heap = Heap([1, 2]) for i in [2, 1]: assert heap.extract_max() == i # Reversed, n = 2 heap = Heap([2, 1]) for i in [2, 1]: assert heap.extract_max() == i # Sorted, n = 3 heap = Heap([1, 2, 3]) for i in [3, 2, 1]: assert heap.extract_max() == i # Reversed, n = 3 heap = Heap([3, 2, 1]) for i in [3, 2, 1]: assert heap.extract_max() == i # Intercalated, n = 5 heap = Heap([1, 5, 2, 3, 4]) for i in [5, 4, 3, 2, 1]: assert heap.extract_max() == i
def prim(G, root=None): """ Find the minimim spanning tree of a graph using Prim's algorithm. If root is given, use it as the starting node. """ nodes = Heap([(float("inf"), n) for n in G.nodes]) parent = {n: None for n in G.nodes} if root: nodes[root] = 0 mst = set() while nodes: node = nodes.pop()[0] if parent[node] is not None: mst.add((parent[node], node)) for neigh, weight in G[node].items(): if neigh in nodes and weight < nodes[neigh]: nodes[neigh] = weight parent[neigh] = node return mst
def dijkstra_heap(graph,source,stress = False): n_nodes = len(graph) Q = [True] * n_nodes dist = [MAX_INT] * n_nodes #distance from source to v prev = [None] * n_nodes #previous node in optimal path dist[source] = 0 S = Heap() for node,distance in enumerate(dist): S.insert((distance,node)) while S.size != 0: #find vertex with minimum distance dist_u , u = S.pop() #instead of finding the minimum we just grab it. O(logn) vs O(n) Q[u] = False weights = graph[u] for v,edge in enumerate(weights): # can I find a way to relate this to the decrease priority? # yes. we need to iterate the heap itself and not the weight array if edge != MAX_INT and Q[v]: #v is in Q and is neighbor #we need some way of relating this to the heap alt = dist_u + edge #alternative path if alt < dist[v]: #alternative path is better dist[v] = alt prev[v] = u S.decrease_priority(v,alt) if stress: #progress tracker - to be removed print(str(S.size)+'\r',end = '') return (dist,prev)
def _build_a_heap(): heap = Heap() while len(heap) < len(NUMBERS): heap.push(random.choice(NUMBERS)) return heap
def test_init(): u"""Assert the succesful initiation of heap object.""" heap = Heap() assert isinstance(heap, Heap)