Learn Algorithm Design by Building a Shortest Path Algorithm - Step 50

Tell us what’s happening:

I’ve tried many different variations but can’t seem to find the right one. Also tried similar to other posts but none of them worked for me. Any help/ideas to right path would be greatly appreciated.

Create a for loop to iterate over targets_to_print and print the following f-string: f’\n{start}-{node} distance: {distances[node]}\nPath: {" → ".join(paths[node])}'.

I’ve also tried to add ‘pass’ in loop body

Your code so far

my_graph = {
    'A': [('B', 3), ('D', 1)],
    'B': [('A', 3), ('C', 4)],
    'C': [('B', 4), ('D', 7)],
    'D': [('A', 1), ('C', 7)]

def shortest_path(graph, start, target = ''):
    unvisited = list(graph)
    distances = {node: 0 if node == start else float('inf') for node in graph}
    paths = {node: [] for node in graph}
    while unvisited:
        current = min(unvisited, key=distances.get)
        for node, distance in graph[current]:
            if distance + distances[current] < distances[node]:
                distances[node] = distance + distances[current]
                if paths[node] and paths[node][-1] == node:
                    paths[node] = paths[current][:]

# User Editable Region

    targets_to_print = [target] if target else graph
        for node in targets_to_print:
            print(f'\n{start}-{node} distance: {distances[node]}\nPath: {" -> ".join(paths[node])}')

shortest_path(my_graph, 'A')

# User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4 Safari/605.1.15

Challenge Information:

Learn Algorithm Design by Building a Shortest Path Algorithm - Step 50

Nvm, I got it.
Make sure you guys check your indentations.

1 Like