예제 #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
예제 #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
예제 #3
0
    for u in list0:
        for v in g.neighbors(u):
            in_degrees[v] -= 1
            if in_degrees[v] == 0:
                list0.append(v)

    return len(list0) == len(g.vertices)


if __name__ == '__main__':
    dress_order = [['shirt', 'tie'], ['tie', 'jacket'], ['belt', 'jacket'],
                   ['shirt', 'belt'], ['undershorts', 'pants'],
                   ['pants', 'shoes'], ['socks', 'shoes']]
    g = Digraph()
    g.add_edges_from(dress_order)
    g.add_vertex('jacket')
    g.add_vertex('watch')
    g.add_vertex('shoes')
    print(g)
    print(is_directed_acyclic_graph(g))
    print(is_directed_acyclic_dfs(g))
    # print(is_directed_acyclic_bfs(g))

    # g1 = Digraph()
    # g1.add_vertex(1)
    # g1.add_vertex(2)
    # print(is_directed_acyclic_bfs(g1))

    # g2 = Digraph()
    # g2.add_edge(1, 2)
    # g2.add_edge(1, 3)
예제 #4
0
# def topological_sort3(g):
#     in_degrees = defaultdict(int)
#
#     for u in g.vertices:
#         in_degrees[u] += 0
#         for v in g.neighbors(u):
#             in_degrees[v] += 1
#
#     list0 = [k for k, v in in_degrees.items() if v == 0]  # vertices with in-degree = 0
#     result = list0.copy()
#     for u in list0:
#         for v in g.neighbors(u):
#             in_degrees[v] -= 1
#             if in_degrees[v] == 0:
#                 result.append(v)
#
#     return result

if __name__ == '__main__':
    dress_order = [['shirt', 'tie'], ['tie', 'jacket'], ['belt', 'jacket'],
                   ['shirt', 'belt'], ['undershorts', 'pants'],
                   ['undershorts', 'shoes'], ['pants', 'shoes'],
                   ['pants', 'belt'], ['socks', 'shoes']]
    g = Digraph()
    g.add_edges_from(dress_order)
    g.add_vertex('watch')
    print(g)
    print(topological_sort(g))
    print(topological_sort2(g))