Ejemplo n.º 1
0
def dijkstra(graph, start, end):
    """Calculate the shortest path."""
    g = Graph(graph)
    final = {}
    # all_visited = []
    visited, d = [], deque([start])
    while d:
        vertex = d.pop()
        visited.append(vertex)
        if g.neighbors(vertex):
            d.extend(g.neighbors(vertex))
            continue

        # FIND THE WEIGHT OF THIS PATH
        try:
            weight = 0
            for idx in range(len(visited)):
                weight += int(g.weight(visited[idx], visited[idx + 1]))
        except IndexError:
            pass

        path = list(visited)
        final[weight] = path

        #
        print(visited)
        try:
            print(d)
            for item in range(len(visited)):
                if g.neighbors(visited[-item - 1]) not in d:
                    visited.pop()
                else:
                    break
        except IndexError:
            pass
        print(visited)

        break
    print('################')
    # print('WEIGHT: ' + str(weight))
    # print('FINAL PATH: ' + str(path))
    print(final)
Ejemplo n.º 2
0
def dijkstra(graph, start, end):
    """Calculate the shortest path."""
    g = Graph(graph)
    final = {}
    # all_visited = []
    visited, d = [], deque([start])
    while d:
        vertex = d.pop()
        visited.append(vertex)
        if g.neighbors(vertex):
            d.extend(g.neighbors(vertex))
            continue

        # FIND THE WEIGHT OF THIS PATH
        try:
            weight = 0
            for idx in range(len(visited)):
                weight += int(g.weight(visited[idx], visited[idx + 1]))
        except IndexError:
            pass

        path = list(visited)
        final[weight] = path

        #
        print(visited)
        try:
            print(d)
            for item in range(len(visited)):
                if g.neighbors(visited[-item - 1]) not in d:
                    visited.pop()
                else:
                    break
        except IndexError:
            pass
        print(visited)

        break
    print('################')
    # print('WEIGHT: ' + str(weight))
    # print('FINAL PATH: ' + str(path))
    print(final)
Ejemplo n.º 3
0
def test_neighbor(node, n, result):
    """Test to check that the correct node have the right edge."""
    from weight_graph import Graph
    g = Graph()
    for idx in node:
        g.add_node(idx)
    g.add_edge(1, 1)
    g.add_edge(1, 4)
    g.add_edge(4, 2)
    g.add_edge(3, 5)
    assert g.neighbors(n) == result