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

hey guys! im stuck here:

Step 30

Dictionary comprehensions support conditional if/else syntax too:

{key: val_1 if condition else val_2 for key in dict}

Use a dictionary comprehension to create a dictionary based in graph and assign it to the distances variable. Give the key a value of zero if the node is equal to the starting node, and infinite otherwise. Use float('inf') to achieve the latter.

as i see it i assigned everything right, cant be an indention problem if its in one line right? please help me finding my brain fart… :slight_smile:

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 node==start else:node=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 (Macintosh; Intel Mac OS X 10_15_7) 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 30

Are you assigning or comparing here?

{key: val_1 if condition else val_2 for key in dict}

If you look at the example again, you don’t see a colon after “else”

key: val_1

Also see how they assign a value to a key here

else val_2 

and how a value is assigned to the key using else (no mention of the key, no equals sign)

Try to use the exact same syntax as the example but substitute your variable names.

1 Like

Thank you for breaking it down for knobheads like me!sometimes i seem to need to be pushed to cognition. :stuck_out_tongue: i got it now! had to get the fact first that the “node:” at the beginning already mentions it for the whole thing! ! one question just to understand the behinds…is there any logical reason that else is normally followed by colons but not here?

1 Like

That’s actually the syntax to write an if statement on one line:

https://www.golinuxcloud.com/python-if-else-one-line/

a = "positive" if b >= 0 else "negative"

aka ternary operator:

https://www.geeksforgeeks.org/ternary-operator-in-python/

min = a if a < b else b

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.