Exemplo n.º 1
0
def random_graph(n, p, directed=False):
    """
    Create a random graph

    :param n: number of nodes
    :param p: probability of edge creation (0 to 100)
    :param directed: set to True to generate a directed graph. Default is False (undirected graph)
    :return: graph
    """
    if not directed:
        g = Graph()
        for i in range(n):
            g.add_vertex(i)
        for u, v in combinations(g.vertices, 2):
            # print(u, v)
            if randrange(1, 101) <= p:
                g.add_edge(u, v)
        return g
    else:
        dg = Digraph()
        for i in range(n):
            dg.add_vertex(i)
        for u, v in permutations(dg.vertices, 2):
            # print(u, v)
            if randrange(1, 101) <= p:
                dg.add_edge(u, v)
        return dg
Exemplo n.º 2
0
def transpose(g):
    gt = Digraph()
    for u in g.vertices:
        gt.add_vertex(u)
    for u, v in g.edges:
        gt.add_edge(v, u, g.weight(u, v))
    return gt
Exemplo n.º 3
0
#         curr = vertex
#         while pred[curr] != source and pred[curr] is not None:
#             dfs_path.appendleft(pred[curr])
#             curr = pred[curr]
#         if pred[curr] is None:
#             dfs_path = []
#         else:
#             dfs_path.appendleft(pred[curr])
#         # print('path from ' + source + ' to ' + vertex + ' ' + str(bfs_path))
#         print(f'path from {source} to {vertex} : {str(list(dfs_path)):20}  '
#               f'discovery at {dtime[vertex]} finishing at {ftime[vertex]}')
#     print('')

if __name__ == '__main__':
    dg = Digraph()
    dg.add_edge('u', 'v')  # Cormen book example
    dg.add_edge('u', 'x')
    dg.add_edge('v', 'y')
    dg.add_edge('w', 'y')
    dg.add_edge('w', 'z')
    dg.add_edge('x', 'v')
    dg.add_edge('y', 'x')
    dg.add_edge('z', 'z')

    print('Digraph:', dg)
    print('Vertices:', dg.vertices)
    print('Edges:', dg.edges)
    print('')

    print('dfs print ', end='')
    dfs_print_vertices(dg)
Exemplo n.º 4
0
#     n = len(g.vertices())
#     edges = g.edges()
#     t = [[[0] * n for _ in range(n)] for _ in range(n + 1)]
#     for i in range(n):
#         for j in range(n):
#             if i == j or (i + 1, j + 1) in edges:
#                 t[0][i][j] = 1
#     for k in range(1, n + 1):
#         for i in range(n):
#             for j in range(n):
#                 t[k][i][j] = t[k - 1][i][j] or (t[k - 1][i][k - 1] and t[k - 1][k - 1][j])
#     return t

if __name__ == '__main__':
    dg = Digraph()
    dg.add_edge(2, 3)
    dg.add_edge(2, 4)
    dg.add_edge(3, 2)
    dg.add_edge(4, 1)
    dg.add_edge(4, 3)

    print(dg)
    print(dg.edges())
    t = transitive_closure(dg)

    # for i, tc in enumerate(t):
    #     print(f't[{i}]')
    #     for row in tc:
    #         print(row)

    for row in t: