mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2025-12-25 02:14:11 -05:00
1.5 KiB
1.5 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 65577a17564ce8a8e06c1460 | Step 35 | 20 | step-35 |
--description--
Dictionary comprehensions support conditional if/else syntax too:
{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.
({ 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--
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--