Back to Freecodecamp

Step 35

curriculum/challenges/english/blocks/learn-algorithm-design-by-building-a-shortest-path-algorithm/65577a17564ce8a8e06c1460.md

latest1.4 KB
Original Source

--description--

Dictionary comprehensions support conditional if/else syntax too:

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

In the example above, dict is the existing dictionary. When condition evaluates to True, key will have the value val_1 , otherwise val_2.

Use a dictionary comprehension to create a dictionary based on 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.

--hints--

You should use the dictionary comprehension syntax to give a value to your distances variable.

js
({ test: () =>  {
    const shortest = __helpers.python.getDef(code, "shortest_path");
    const {function_body} = shortest;
    assert(function_body.match(/^\s{4}distances\s*=\s*\{\s*(\w+)\s*:\s*0\s+if\s+(?:\1\s*==\s*start|start\s*==\s*\1)\s+else\s+float\s*\(\s*("|')inf\2\s*\)\s+for\s+\1\s+in\s+graph\s*\}/m));
  }
})

--seed--

--seed-contents--

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

--fcc-editable-region--
def shortest_path(graph, start):
    unvisited = list(graph)
    distances = {}
    paths = {node: [] for node in graph}
    print(f'Unvisited: {unvisited}\nDistances: {distances}')
    
shortest_path(my_graph, 'A')
--fcc-editable-region--