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

Tell us what’s happening:

I have no clue what to do. Pease help me with this.

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)]
}


# User Editable Region

def shortest_path(graph, start):
    unvisited = list(graph)
    distances = {node: 0 if start else float('inf') for node in graph}
    paths = {node: [] for node in graph}
    print(f'Unvisited: {unvisited}\nDistances: {distances}')
    
shortest_path(my_graph, 'A')

# User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36

Challenge Information:

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

1 Like

So after going through your code, I see the small issue here:

  1. Original Code: The condition 0 if start always assigns 0 to all nodes because the start is a non-empty string (which is always truthy), so the condition evaluates to 0 for every node.

  2. Fix: To fix this, think about how you can compare each node in the graph to the start node. You want to set the distance to 0 only for the starting node, and float(‘inf’) for all the others. Like how could you modify the condition to compare each node with start?

Let us know if you need more help. Good luck!

I’m still a little lost.

Hi. The condition between your “if” and “else” is start (see the example code for the condition placement). Set out what is your condition doing and then compare it to the condition the instructions are asking for.

In what way? Do you have a question about something?

You’re very close! Instead of using 0 if start, think of it as assigning 0 only to the start node, and infinity to all other nodes. This way, you’re ensuring that only the start node gets a distance of 0 and the rest get infinity initially. That should fix the issue. Let us know if you’re still having trouble.