The shortest_distances variable contains the following data at the end of the shortest_path function:
{
'A': (0, 'A'),
'B': (10, 'A'),
'C': (30, 'B'),
'D': (35, 'A'),
'E': (36, 'C')
}
We can use this information to nicely display the full path between A and E. Starting from the end node, E, shortest_distances["E"][1] contains the previous node in the shortest path. Similarly, shortest_distances["C"][1] contains the previous node in the shortest path from A to E and so on.
We can write the following function to retrieve each node and distance in the path:
def nice_path(start_node, end_node, shortest_distances):
node = end_node
result = []
while node != start_node:
result.append((node, shortest_distances[node][0]))
node = shortest_distances[node][1]
result.append((start_node, 0)...