Hello! I have tried multiple times to solve this problem, I put the paths[node] at the beginning of the if, but it didn’t work. I also tried the code I have right here (The editable region) and it also didn’t work. Can someone give me the answer and explain it a bit because I can’t seem to find it?
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):
unvisited = list(graph)
distances = {node: 0 if node == start else float('inf') for node in graph}
paths = {node: [] for node in graph}
paths[start].append(start)
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]
# User Editable Region
paths[node][-1] == node if paths[node] != []:
paths[node] = paths[current]
# User Editable Region
else:
paths[node].extend(paths[current])
paths[node].append(node)
unvisited.remove(current)
print(f'Unvisited: {unvisited}\nDistances: {distances}\nPaths: {paths}')
#shortest_path(my_graph, 'A')
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36
Challenge Information:
Learn Algorithm Design by Building a Shortest Path Algorithm - Step 45
You can check if a value is true or false like this. If a is 0, it will be false, but if it’s > 0, it will be true. You can use this to check if a list is empty (false) or non empty (true). So you don’t need an equal sign, you can just say
if a:
you don’t need
if a == True:
#or
if a > 0:
Secondly, you’ll need to check that paths[node] is non-empty first, so you need to reverse the order of your if statement. This is because you want to check if it’s non-empty first and then you want to check paths[node][-1] == node
Can you tell me what [Learn Algorithm Design by Building a Shortest Path Algorithm] is showing/teaching in these 54 steps? So I can find a youtube video about it to understand more.
I haven’t actually done this new curriculum yet, so I couldn’t say.
The way these are designed though is that you will learn many smaller details (the if... and... structure here) while putting together a bigger CS concept (Shortest Path algorithm)
If you have a question about a specific challenge as it relates to your written code for that challenge and need some help, click the Ask for Help button located on the challenge (it looks like a question mark). This button only appears if you have tried to submit an answer at least three times.
The Ask for Help button will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.