当前位置: 首页>>代码示例>>Python>>正文


Python Graph.build方法代码示例

本文整理汇总了Python中src.graph.Graph.build方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.build方法的具体用法?Python Graph.build怎么用?Python Graph.build使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在src.graph.Graph的用法示例。


在下文中一共展示了Graph.build方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_bellman_ford_with_non_negative_cycle

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
    def test_bellman_ford_with_non_negative_cycle(self):
        """ Given the following graph from the lecture:
                  -2
            (a)-------->(b)
            ^|           |
             |           |
             4\       -1/
               \       /
                \(c)</
                 /  \
               2/    \-3
              v/      \v
             (x)       (y)
              \^       /^
               \      /
               1\    /-4
                 \  /
                 (z)
        And and a vertex (s) that is connected to all other vertices through
        edges of cost 0.
        """
        g = Graph.build(edges=[('a', 'b', -2), ('c', 'a', 4), ('b', 'c', -1),
                ('c', 'x', 2), ('c', 'y', -3), ('z', 'x', 1), ('z', 'y', -4)],
                directed=True)
        g.add_vertex('s')
        for vertex in g.get_vertices():
            g.add_edge(('s', vertex, 0))

        (costs, __) = shortest_path(g, 's', return_paths=False)
        expected_costs = {'a': 0, 'c': -3, 'b': -2, 's': 0,'y': -6, 'x': -1,'z': 0}
        self.assertEqual(costs, expected_costs,
            'should produce the correct costs')
开发者ID:mindis,项目名称:learn,代码行数:34,代码来源:test_bellman_ford_shortest_path.py

示例2: kruskal_union_find_mst

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
def kruskal_union_find_mst(graph):
    """ Uses Kruskel's greedy algorithm to compute the MST of graph.

    Running time: O(m*log n) - where m is the number of edges and n is the
        number of vertices.

    Params:
        graph: object, instance of src.graph.Graph

    Returns:
        object, src.graph.Graph instance reperesenting the MST.
    """
    mst_edges = []
    edges = graph.get_edges()
    num_vertices = len(graph.get_vertices())

    edges = graph.get_edges()
    edges.sort(key=lambda e: e[2])

    union_find = UnionFind()

    index = 0
    while index < num_vertices:
        edge = edges[index]
        [tail, head, value] = graph.split_edge(edge)
        index += 1

        if union_find.find(head) == union_find.find(tail):
            continue
        else:
            union_find.union(head, tail)
        mst_edges.append(edge)

    mst = Graph.build(edges=mst_edges, directed=False)
    return mst
开发者ID:mindis,项目名称:learn,代码行数:37,代码来源:minimum_spanning_tree.py

示例3: test_johnson

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
    def test_johnson(self):
        """ Given the following graph from the lecture:
                  -2
            (a)-------->(b)
            ^|           |
             |           |
             4\       -1/
               \       /
                \(c)</
                 /  \
               2/    \-3
              v/      \v
             (x)       (y)
              \^       /^
               \      /
               1\    /-4
                 \  /
                 (z)
        """
        g = Graph.build(edges=[('a', 'b', -2), ('c', 'a', 4), ('b', 'c', -1),
                ('c', 'x', 2), ('c', 'y', -3), ('z', 'x', 1), ('z', 'y', -4)],
                directed=True)

        actual = johnson(g)
        expected = {
            'a': {'a': 0, 'c': -3, 'b': -2, 'y': -6, 'x': -1, 'z': INF},
            'c': {'a': 4, 'c': 0, 'b': 2, 'y': -3, 'x': 2, 'z': INF},
            'b': {'a': 3, 'c': -1, 'b': 0, 'y': -4, 'x': 1, 'z': INF},
            'y': {'a': INF, 'c': INF, 'b': INF, 'y': 0, 'x': INF, 'z': INF},
            'x': {'a': INF, 'c': INF, 'b': INF, 'y': INF, 'x': 0, 'z': INF},
            'z': {'a': INF, 'c': INF, 'b': INF, 'y': -4, 'x': 1, 'z': 0}
        }
        self.assertEqual(actual, expected,
            'should return correct all pairs shortest path distances')
开发者ID:mindis,项目名称:learn,代码行数:36,代码来源:test_all_pairs_shortest_paths.py

示例4: test_scc

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
    def test_scc(self):
        """ Given the following graph it computes SCCs in it.

             />(2)---------->(8)----------v
            /   |               \     /->(10)
          (1)   |                v  /      |
            ^\  v          /---->(9)<-\    v
              \(3)----->(4)            \-(11)
                 \      ^| \            /^
                  \    / |  v         /
                   >(5)  |   (7)----/
                      ^\ |   /
                        \v  v
                         (6)
        """
        g = Graph.build(edges=[(1,2), (3,2), (2,3), (3,4), (3,5), (5,4),
                               (4,6), (4,7), (7,6), (6,5), (4,9), (7, 11),
                               (11,9), (9,10), (10,11), (2,8), (8,9), (8,10)],
                        directed=True)
        connected_components = scc(g)
        expected = [[8], [1], [2, 3], [9, 10, 11], [4, 5, 6, 7]]

        self.assertEqual(len(connected_components), len(expected),
                'should return the same number of components')
        for component in connected_components:
            self.assertIn(component, expected,
                'should detect strongly connected components')
开发者ID:mindis,项目名称:learn,代码行数:29,代码来源:test_strongly_connected_components.py

示例5: test_shortest_path_heap_case3

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
    def test_shortest_path_heap_case3(self):
        """ Compute a shortest path using the heap implementation. """
        g = Graph.build(edges=[
            ('a','b',1),('a','c',4),('a','d',4),('b','c',1),('c','d',1)],
            directed=True)

        shortest_path = shortest_path_heap(g, 'a')
        self.assertEqual(shortest_path['d'], 3)
开发者ID:mindis,项目名称:learn,代码行数:10,代码来源:test_dijkstra_shortest_path.py

示例6: test_cluster_graph

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
    def test_cluster_graph(self):
        """ The graph is specified in distances but it should look something
        like this:
        | *a
        |                                *e
        |                          *c
        |
        |
        |
        |
        |                          *d
        |                                *f
        | *b
        +--------------------------------------------->
        """
        g = Graph.build(edges=[
            ('a', 'e', 8), ('a', 'c', 7), ('a', 'd', 9), ('a', 'f', 10), ('a', 'b', 8),
            ('e', 'f', 6), ('e', 'd', 5), ('e', 'b', 10), ('e', 'c', 1),
            ('c', 'f', 5), ('c', 'd', 4), ('c', 'b', 9),
            ('d', 'f', 1), ('d', 'b', 7),
            ('f', 'b', 8)
        ], directed=False)

        (clusters, distances) = cluster_graph(g, 4)
        expectedClusters = {
            'a': ['a'],
            'c': ['c', 'e'],
            'b': ['b'],
            'd': ['d', 'f']
        }
        expectedDistances = {
            ('b', 'c'): 9,
            ('c', 'd'): 4,
            ('a', 'd'): 9,
            ('a', 'b'): 8,
            ('a', 'c'): 7,
            ('b', 'd'): 7
        }
        self.assertEqual(clusters, expectedClusters,
            'should return correct clusters')
        self.assertEqual(distances, expectedDistances,
            'should compute distances')

        (clusters, distances) = cluster_graph(g, 3)
        expectedClusters = {
            'a': ['a'],
            'b': ['b'],
            'c': ['c', 'e', 'd', 'f']
        }
        expectedDistances = {
            ('b', 'c'): 7,
            ('a', 'b'): 8,
            ('a', 'c'): 7
        }
        self.assertEqual(clusters, expectedClusters,
            'should return correct clusters')
        self.assertEqual(distances, expectedDistances,
            'should compute distances')
开发者ID:mindis,项目名称:learn,代码行数:60,代码来源:test_clustering.py

示例7: prims_heap_mst

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
def prims_heap_mst(graph):
    """ Computes minimal spanning tree using a heap data structure to store
    unexplored vertices.

    The difference is that it maintains the frontier of the explored MST in a
    heap, as such always computing the min vertex in O(logm), where m is the
    number of edges.

    The heap is used to store the vertices not the edges as in the previous
    implementation. The heap maintains two invariants:
    1. elements in the heap are vertices not yet explored
    2. keys under which each vertex is stored in the heap is the minimum weight
    of an edge incident on the vertex whose tail is already in the MST.

    Complexity: O(m*log n), m - number of edges, n - number of vertices

    Args:
        graph: object, data structure to hold the graph data.

    Returns:
        A Graph instance reperesenting the MST.
    """
    mst_vertices = []
    mst_edges = []
    INF = float('inf')
    vertices = graph.get_vertices()
    num_vertices = len(vertices)

    frontier = VertexHeap.heapify([(v, INF) for v in vertices])
    vertex = random.choice(graph.get_vertices())
    frontier.remove(vertex)

    # This dict stores for each vertex the neighbour with the smallest edge,
    # and the edge cost. Format {vertex: (incident_vertex, edge_cost)}
    vertices = {}

    while vertex:
        mst_vertices.append(vertex)
        if len(mst_vertices) == num_vertices:
            break

        for edge in graph.egress(vertex):
            [__, head, cost] = graph.split_edge(edge)
            if head not in mst_vertices:
                [__, head_key] = frontier.remove(head)
                min_cost = min(cost, head_key)
                frontier.insert((head, min_cost))
                if min_cost < head_key:
                    vertices[head] = (vertex, cost)

        # Extract the vertex with min cost and compute it's associated min edge.
        (head, __) = frontier.extract_min()
        (tail, cost) = vertices[head]
        mst_edges.append((tail, head, cost))
        vertex = head

    mst = Graph.build(edges=mst_edges, directed=False)
    return mst
开发者ID:mindis,项目名称:learn,代码行数:60,代码来源:minimum_spanning_tree.py

示例8: test_contract

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
    def test_contract(self):
        g = Graph.build(edges=[(1,2), (2,3), (3,1)])
        g = contract(g, (1,2))

        self.assertIn('1_2', g.table, '1 and 2 have fused')
        self.assertIn(3, g.table['1_2'], '1 and 2 have fused')
        self.assertIn(3, g.table, '1 and 2 have fused')
        self.assertIn('1_2', g.table[3], '1 and 2 have fused')
        self.assertNotIn(2, g.get_vertices(), 'no more 2 vertex')
开发者ID:mindis,项目名称:learn,代码行数:11,代码来源:test_minimum_cut.py

示例9: test_get_sync_vertices

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
 def test_get_sync_vertices(self):
     """ Given the graph below it should find 1 and 2 as sync vertices:
     (1) <- (3)
            /
     (2) <-/
     """
     g = Graph.build(edges=[(3,1), (3,2)], directed=True)
     actual = get_sync_vertices(g)
     expected = [1, 2]
     self.assertEqual(actual, expected, 'found sync vertices')
开发者ID:mindis,项目名称:learn,代码行数:12,代码来源:test_topological_ordering.py

示例10: test_shortest_path_naive_case1

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
    def test_shortest_path_naive_case1(self):
        """ Compute a shortest path using the heap implementation. """
        g = Graph.build(edges=[
            ('a','c',3),('c','b',10),('a','b',15),('d','b',9),
            ('a','d',4),('d','f',7),('d','e',3),('e','g',1),
            ('e','f',5),('g','f',2),('f','b',1)],
            directed=True)

        shortest_path = shortest_path_naive(g, 'a')
        self.assertEqual(shortest_path['g'], 8)
        self.assertEqual(shortest_path['b'], 11)
开发者ID:mindis,项目名称:learn,代码行数:13,代码来源:test_dijkstra_shortest_path.py

示例11: test_randomized_cut

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
 def test_randomized_cut(self):
     """ Tests that the following graph is split correctly.
     (a)--(c)
      |  / |
     (b)--(d)
     """
     g = Graph.build(edges = [('a', 'b'), ('a', 'c'),
                              ('b', 'c'), ('b', 'd'),
                              ('c', 'd')])
     compacted = randomized_cut(g)
     self.assertEqual(len(compacted.get_vertices()), 2,
             'should have compacted to only 2 vertices')
开发者ID:mindis,项目名称:learn,代码行数:14,代码来源:test_minimum_cut.py

示例12: test_topological_ordering

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
 def test_topological_ordering(self):
     """ Given the following graph:
       /-->(b)-->\
     (a)         (d)
       \-->(c)-->/
     """
     g = Graph.build(edges=[('a','b'), ('a', 'c'), ('b', 'd'), ('c', 'd')],
                     directed=True)
     ordering = dfs_loop(g)
     self.assertEqual(ordering['a'], 1)
     self.assertIn(ordering['b'], [2,3])
     self.assertIn(ordering['c'], [2,3])
     self.assertEqual(ordering['d'], 4)
开发者ID:mindis,项目名称:learn,代码行数:15,代码来源:test_topological_ordering.py

示例13: test_kruskal_suboptimal_mst_2

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
 def test_kruskal_suboptimal_mst_2(self):
     g = Graph.build(edges=[('a', 'b', 3), ('a', 'f', 2), ('f', 'g', 7),
             ('b', 'd', 16), ('d', 'e', 11), ('f', 'e', 1), ('g', 'e', 6),
             ('g', 'h', 15), ('e', 'h', 5), ('b', 'c', 17), ('c', 'd', 8),
             ('d', 'i', 4), ('c', 'i', 18), ('e', 'i', 10), ('h', 'i', 12),
             ('i', 'j', 9), ('h', 'j', 13)],
         directed=False)
     mst = kruskal_suboptimal_mst(g)
     expected = sorted([('a', 'b', 3), ('a', 'f', 2), ('e', 'f', 1),
             ('e', 'g', 6), ('e', 'h', 5), ('e', 'i', 10), ('d', 'i', 4),
             ('c', 'd', 8), ('i', 'j', 9)])
     actual = sorted(mst.get_edges())
     self.assertEqual(actual, expected, 'should compute the correct mst')
开发者ID:mindis,项目名称:learn,代码行数:15,代码来源:test_minimum_spanning_tree.py

示例14: test_randomized_cut_for_larger_graph

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
 def test_randomized_cut_for_larger_graph(self):
     """ Test minimum cut for a larger graph.
     (a)--(b)--(e)--(f)
      |  X |    |  X |
     (c)--(d)--(g)--(h)
     """
     g = Graph.build(edges = [('a', 'b'), ('a', 'c'), ('a', 'd'),
                              ('b', 'c'), ('b', 'd'), ('b', 'e'),
                              ('c', 'd'), ('d', 'g'),
                              ('e', 'g'), ('e', 'f'), ('e', 'h'),
                              ('f', 'g'), ('f', 'h'), ('g', 'h')])
     compacted = randomized_cut(g)
     self.assertEqual(len(compacted.get_vertices()), 2,
             'should have compacted to only 2 vertices')
开发者ID:mindis,项目名称:learn,代码行数:16,代码来源:test_minimum_cut.py

示例15: test_get_frontier

# 需要导入模块: from src.graph import Graph [as 别名]
# 或者: from src.graph.Graph import build [as 别名]
    def test_get_frontier(self):
        """ Makes sure frontier edges are correctly picked.
            (1)--->(2)
             |      |
             V      V
            (3)<---(4)
        """
        g = Graph.build(edges=[(1,2), (1,3), (2,4), (4,3)], directed=True)
        explored_vertices = [1,3]

        actual = get_frontier(g, explored_vertices)
        expected = set([(1,2,True)])
        self.assertEqual(actual, expected, 'should only return the only node ' \
                                      'reachable that has not yet been visited')
开发者ID:mindis,项目名称:learn,代码行数:16,代码来源:test_dijkstra_shortest_path.py


注:本文中的src.graph.Graph.build方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。