简体   繁体   中英

small graph and networkx

Is there a way to declare that simple graph in networkx :

simple_graph = {
    'A': ['B'],
    'B': ['A', 'C', 'D'],
    'C': ['A'],
    'D': ['E', 'A', ''],
    'E': ['B', '']
    }

in a easier way (more compact) than this :

g.add_edges_from([('A', 'B'), ('B', 'A'), ('B', 'C'), ('B', 'D'),
                  ('C', 'A'), ('D', 'E'), ('D', 'A'), ('E', 'B')])

or not ?

Can't you just create the graph and remove the node (or nodes if necessary), eg:

import networkx as nx

simple_graph = {
    'A': ['B'],
    'B': ['A', 'C', 'D'],
    'C': ['A'],
    'D': ['E', 'A', ''],
    'E': ['B', '']
    }

g = nx.DiGraph(simple_graph)
g.remove_node('')

Then g.edges() will give you:

OutEdgeView([('A', 'B'), ('E', 'B'), ('D', 'A'), ('D', 'E'), ('B', 'A'), ('B', 'C'), ('B', 'D'), ('C', 'A')])

Here is one approach:

In [84]: simple_graph = {
    'A': ['B'],
    'B': ['A', 'C', 'D'],
    'C': ['A'],
    'D': ['E', 'A', ''],
    'E': ['B', '']
    }

In [85]: [(k, item) for k, v in simple_graph.items() for item in v if item]
Out[85]: 
[('A', 'B'),
 ('C', 'A'),
 ('B', 'A'),
 ('B', 'C'),
 ('B', 'D'),
 ('E', 'B'),
 ('D', 'E'),
 ('D', 'A')]

This can be done using class as well.

In the code, we create two classes: Graph, which holds the master list of vertices, and Vertex, which represents each vertex in the graph:

class Vertex:
    def __init__(self, node):
        self.id = node
        self.adjacent = {}

    def __str__(self):
        return str(self.id) + ' adjacent: ' + str([x.id for x in self.adjacent])

    def add_neighbor(self, neighbor, weight=0):
        self.adjacent[neighbor] = weight

    def get_connections(self):
        return self.adjacent.keys()  

    def get_id(self):
        return self.id

    def get_weight(self, neighbor):
        return self.adjacent[neighbor]

class Graph:
    def __init__(self):
        self.vert_dict = {}
        self.num_vertices = 0

    def __iter__(self):
        return iter(self.vert_dict.values())

    def add_vertex(self, node):
        self.num_vertices = self.num_vertices + 1
        new_vertex = Vertex(node)
        self.vert_dict[node] = new_vertex
        return new_vertex

    def get_vertex(self, n):
        if n in self.vert_dict:
            return self.vert_dict[n]
        else:
            return None

    def add_edge(self, frm, to, cost = 0):
        if frm not in self.vert_dict:
            self.add_vertex(frm)
        if to not in self.vert_dict:
            self.add_vertex(to)

        self.vert_dict[frm].add_neighbor(self.vert_dict[to], cost)
        self.vert_dict[to].add_neighbor(self.vert_dict[frm], cost)

    def get_vertices(self):
        return self.vert_dict.keys()

if __name__ == '__main__':

    g = Graph()

    g.add_vertex('a')
    g.add_vertex('b')
    g.add_vertex('c')
    g.add_vertex('d')
    g.add_vertex('e')
    g.add_vertex('f')

    g.add_edge('a', 'b', 7)  
    g.add_edge('a', 'c', 9)
    g.add_edge('a', 'f', 14)
    g.add_edge('b', 'c', 10)
    g.add_edge('b', 'd', 15)
    g.add_edge('c', 'd', 11)
    g.add_edge('c', 'f', 2)
    g.add_edge('d', 'e', 6)
    g.add_edge('e', 'f', 9)

    for v in g:
        for w in v.get_connections():
            vid = v.get_id()
            wid = w.get_id()
            print '( %s , %s, %3d)'  % ( vid, wid, v.get_weight(w))

    for v in g:
        print 'g.vert_dict[%s]=%s' %(v.get_id(), g.vert_dict[v.get_id()])

Src: http://www.bogotobogo.com/python/python_graph_data_structures.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM