def heap_sort(values: List[int]) -> List[int]: heap = Heap() sorted_values = [] for value in values: heap.insert(f'node_{value}', value) while len(sorted_values) < len(values): name, value = heap.pop_min() sorted_values.append(value) return sorted_values
def dijkstra(self, node_key: str, node_destination_key: str) -> List[Tuple[str, int]]: """ Method that returns the shortest path between 2 nodes We will store for each node its parent(previous_node) We will store the distances from source node in a distances registry 1. At first the distance registry is set to infinite except for the source node 2. We will use a heap, in which we temporarily store the nodes to visit 3. The heap will allow us to retrieve the next node with minimal distance from source node 4. From each visited nodes, we will store its neighbors in the heap, and if the distance we found is shorter than the previous one, we update the distance and store it in the heap to be visited. 5. Finally, from the destination key, we will look in the parent registry, and create the path with the distance registry """ heap_instance = Heap() # set the distances registry distances = {} visited = [] previous_node = {} for key in self.nodes.keys(): distances[key] = cmath.inf distances[node_key] = 0 # helper to create path previous_node[node_key] = None heap_instance.insert(node_key, 0) while len(heap_instance.nodes) > 0: heap_node = heap_instance.pop_min() current_key = heap_node[0] visited.append(current_key) for child_key, child_value in self.nodes[current_key].items(): if child_key in visited: continue # At first we have zero, then we take this value and we update it(so we don't deal with inf) new_dist = distances[current_key] + child_value if new_dist < distances[child_key]: distances[child_key] = new_dist heap_instance.insert(child_key, new_dist) previous_node[child_key] = current_key key = node_destination_key path = [] while previous_node[key]: path.insert(0, (key, distances[key])) key = previous_node[key] path.insert(0, (node_key, 0)) return path