mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-04-12 10:00:39 -04:00
2.5 KiB
2.5 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 6559d70c5161b16ff1d6530d | Step 54 | 20 | step-54 |
--description--
Python provides a concise way to write if/else conditionals by using the ternary syntax:
val_1 if condition else val_2
The expression above evaluates to val_1 if condition is true, otherwise to val_2.
Delete your print call and create a variable called targets_to_print after your while loop. Use the ternary syntax to assign it [target] when target is truthy, and graph otherwise.
--hints--
You should delete your print call.
({ test: () => assert.isFalse( /print\s*\(\s*f("|')Unvisited:\s*\{\s*unvisited\s*\}\\nDistances:\s\{\s*distances\s*\}\\nPaths:\s\{\s*paths\s*\}\1\s*\)/.test(code)) })
You should create a variable called targets_to_print after your while loop.
({ test: () => {
const shortest = __helpers.python.getDef(code, "shortest_path");
const {function_body} = shortest;
assert(function_body.match(/unvisited\.remove\(\s*current\s*\).*^\s{4}targets_to_print\s*=/ms));
}
})
You should use the ternary syntax to assign [target] when target is truthy, and graph otherwise to your targets_to_print variable.
({ test: () => {
const shortest = __helpers.python.getDef(code, "shortest_path");
const {function_body} = shortest;
assert(function_body.match(/unvisited\.remove\(\s*current\s*\).*^\s{4}targets_to_print\s*=\s*\[\s*target\s*\]\s+if\s+target\s+else\s+graph/ms));
}
})
--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)]
}
def shortest_path(graph, start, target = ''):
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]
if paths[node] and paths[node][-1] == node:
paths[node] = paths[current][:]
else:
paths[node].extend(paths[current])
paths[node].append(node)
unvisited.remove(current)
--fcc-editable-region--
print(f'Unvisited: {unvisited}\nDistances: {distances}\nPaths: {paths}')
shortest_path(my_graph, 'A')
--fcc-editable-region--