Esempio n. 1
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
Esempio n. 2
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
    def test_topological_sort(self):
        # cp3 4.4 dag in https://visualgo.net/en/dfsbfs
        dg = Digraph()
        dg.add_edges_from([(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (2, 5),
                           (3, 4), (7, 6)])
        self.assertEqual([7, 6, 0, 1, 2, 5, 3, 4], topological_sort(dg))

        # cp3 4.17 dag in https://visualgo.net/en/dfsbfs
        dg = Digraph()
        dg.add_edges_from([(0, 1), (0, 2), (0, 3), (1, 3), (1, 4), (2, 4),
                           (3, 4)])
        self.assertEqual([0, 2, 1, 3, 4], topological_sort(dg))

        # cp3 4.18 dag bipartite in https://visualgo.net/en/dfsbfs
        dg = Digraph()
        dg.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)])
        self.assertEqual([0, 2, 1, 3, 4], topological_sort(dg))
Esempio n. 4
0
    list0 = [k for k, v in in_degrees.items()
             if v == 0]  # vertices with in-degree = 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()
Esempio n. 5
0
    g = Graph()  # clrs Figure B.2(b)
    g.add_edges_from([(1, 2), (1, 5), (2, 5), (3, 6)])
    g.add_vertex(4)
    print(f'connected: {is_connected(g)}')
    # print(connected_components_dj(g))
    print(connected_components(g))
    assert connected_components(g) == [[1, 2, 5], [3, 6], [4]]

    g = Graph()
    g.add_edges_from([(1, 2), (1, 5), (2, 3), (2, 5), (3, 6), (4, 5)])
    print(f'connected: {is_connected(g)}')
    # print(connected_components_dj(g))
    print(connected_components(g))
    assert connected_components(g) == [[1, 2, 3, 6, 5, 4]]

    dg = Digraph()
    dg.add_edges_from([
        ('a', 'b'),
        ('b', 'c'),
        ('b', 'e'),
        ('c', 'd'),
        ('c', 'g'),
        ('d', 'c'),
        ('d', 'h'),
        ('e', 'a'),
        ('e', 'f'),
        ('f', 'g'),
        ('g', 'f'),
        ('g', 'h'),
        ('h', 'h'),
    ])
Esempio n. 6
0
from Graph import Digraph


def topological_sort(g):
    def dfs(g, u):
        seen.add(u)
        for v in g.neighbors(u):
            if v not in seen:
                dfs(g, v)
        sortedv.appendleft(u)

    seen = set()
    sortedv = deque()
    for u in g.vertices:
        if u not in seen:
            dfs(g, u)
    return list(sortedv)


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(topological_sort(g))
Esempio n. 7
0
        if dist[u] < d:  # skip if the value in dist is smaller
            continue
        for v in g.neighbors(u):
            d = dist[u] + g.weight(u, v)
            if d < dist[v]:  # relaxation
                dist[v] = d
                pred[v] = u
                heappush(minq,
                         (dist[v], v))  # could have duplicate vertices in minq
    return pred, dist


# to get the path, refer to the predecessors dictionary

if __name__ == '__main__':
    dg = Digraph()  # clrs example
    dg.add_weighted_edges_from([('s', 't', 10), ('s', 'y', 5), ('t', 'x', 1),
                                ('t', 'y', 2), ('x', 'z', 4), ('y', 't', 3),
                                ('y', 'x', 9), ('y', 'z', 2), ('z', 's', 7),
                                ('z', 'x', 6)])
    print(dg)
    print(dijkstra(dg, 's'))

    print('-----')
    dg = Digraph()  # graph theory example youtube
    dg.add_weighted_edges_from([(0, 1, 4), (0, 2, 1), (1, 3, 1), (2, 1, 2),
                                (2, 3, 5), (3, 4, 3)])
    print(dg)
    print(dijkstra(dg, 0))

    print('-----')
Esempio n. 8
0
#         while pred[curr] != source:
#             if pred[curr] not in sp:  # cycle check
#                 sp.appendleft(pred[curr])
#                 curr = pred[curr]
#             else:
#                 print(f'No path to {v}')
#                 break  # cycles are ignored
#         else:
#             sp.appendleft(source)
#             all_sp.append(list(sp))
#
#     return all_sp


if __name__ == '__main__':
    dg = Digraph()  # clrs example
    dg.add_weighted_edges_from([('t', 'x', 5), ('t', 'y', 8), ('t', 'z', -4), ('x', 't', -2),
                                ('y', 'x', -3), ('y', 'z', 9), ('z', 'x', 7), ('z', 's', 2),
                                ('s', 't', 6), ('s', 'y', 7)])
    print(f'Graph: {dg}')
    print(f'Weights: {dg.weights}')
    print(bellman_ford(dg, 's'))
    print('')

    # dg = Digraph()
    # dg.add_edge('s', 'a', 3)  # cormen book example
    # dg.add_edge('s', 'c', 5)
    # dg.add_edge('s', 'e', 2)
    # dg.add_edge('a', 'b', -4)
    # dg.add_edge('b', 'g', 4)
    # dg.add_edge('c', 'd', 6)
Esempio n. 9
0
            for v in g.neighbors(u):
                queue.append((v, path + [v]))
    return paths


# def all_simple_paths_bfs(g, s, t):
#     seen = set()
#     paths = []
#     queue = deque([(s, s)])
#     while queue:
#         u, path = queue.popleft()
#         if u == t:
#             paths.append(path)
#         else:
#             for v in g.neighbors(u):
#                 if v not in seen:
#                     queue.append((v, path + v))
#                     seen.add(v)
#     return paths

if __name__ == '__main__':
    g = Digraph()  # clrs Figure 22.8
    g.add_edges_from([
        ('m', 'q'), ('m', 'r'), ('m', 'x'), ('n', 'o'), ('n', 'q'), ('n', 'u'),
        ('o', 'r'), ('o', 's'), ('o', 'v'), ('p', 'o'), ('p', 's'), ('p', 'z'),
        ('q', 't'), ('r', 'u'), ('r', 'y'), ('s', 'r'), ('v', 'w'), ('v', 'x'),
        ('y', 'v')
    ])
    print(all_simple_paths_dfs(g, 'p', 'v'))
    print(all_simple_paths_bfs(g, 'p', 'v'))