Как написать эту функцию в функциональном стиле в python? - PullRequest
0 голосов
/ 12 апреля 2020

Существует структурно написанная функция в python, которая реализует алгоритм Дейкстры. Мне нужно написать это в функциональном стиле, но я никогда не писал функционально. Подскажите как это сделать. Вот мой код:

_adj_list = {'A': {'B': 5}}  # vertex adjacency list (e.g. AB = 5)

# the current parameter is the vertex, where to find the shortest paths to all other vertices
# returns the visited dictionary (the result of the algorithm)
def algorithm_dijkstra(current):
    nodes = tuple(_adj_list.keys())

    unvisited = {node: None for node in nodes}
    visited = {}
    current_distance = 0
    unvisited[current] = current_distance

    while True:
        try:
            for neighbour, distance in _adj_list[current].items():
                if neighbour not in unvisited:
                    continue
                new_distance = current_distance + distance
                if unvisited[neighbour] is None or unvisited[neighbour] > new_distance:
                    unvisited[neighbour] = new_distance
            visited[current] = current_distance
            del unvisited[current]
            if not unvisited:
                break
            candidates = [node for node in unvisited.items() if node[1]]
            current, current_distance = sorted(candidates, key=lambda x: x[1])[0]
        except LookupError:
            for key in unvisited:
                visited[key] = 'no way'
            unvisited.clear()
            break

    return visited
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...