Files
2024-05-22 17:27:37 +02:00

2.0 KiB

id, title, challengeType, dashedName
id title challengeType dashedName
655791ae44c182bd92f31caa Step 49 20 step-49

--description--

The .remove() method removes from a list the first matching element that is passed as the argument:

my_list = ['larch', 1, True, 1]
my_list.remove(1)
print(my_list) # Output: ['larch', True, 1]

Terminate the while loop by removing the current node from the unvisited list. Pay attention to the indentation.

--hints--

You should use the .remove() method to remove the current node from unvisited after your for loop.

({ test: () =>  {
    const commentless_code = __helpers.python.removeComments(code);
    const {block_body} = __helpers.python.getBlock(commentless_code, /while\s+unvisited/);
    assert(block_body.match(/^\s+unvisited\.remove\s*\(\s*current\s*\)/m));
    const {block_body: for_body} = __helpers.python.getBlock(commentless_code, /for\s+node\s*,\s*distance\s+in\s+graph\s*\[\s*current\s*\]\s*/);
    assert.notMatch(for_body, /^\s+unvisited\.remove\s*\(\s*current\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)]
}

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)
--fcc-editable-region--    
    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][-1] == node:
                    paths[node] = paths[current]
                else:
                    paths[node].extend(paths[current])
                paths[node].append(node)
--fcc-editable-region--    
    print(f'Unvisited: {unvisited}\nDistances: {distances}\nPaths: {paths}')

#shortest_path(my_graph, 'A')