Skip to content
Advertisement

find number of connected edges to a node and node with max connected edges

In a graph, how do I find the number of connected (directly bound) edges to a node?
And then, it would be trivial, but if there is any direct method to find the unique(s) node(s) with the maximum edges connected to them it would be nice.
I’m using Python 2.7 and Networkx.

Until now, I’m doing like this:

sG            = list(nx.connected_component_subgraphs(G)) # sG is a sub_graph of main graph G
nb_sG         = len(sub_graphs)
max_con_node  = list()
for m in xrange(nb_sG):
    sG_nodes      = [(node, len(sG[m].edges(node)), sG[m].edges(node)) for node in sG[m].nodes()]
    connexions    = [i[1] for i in sG_nodes]
    idx           = [i for i,x in enumerate(connexions) if x==max(connexions)]
    max_con_node.append((max(connexions), [sG_nodes[i][0] for i in idx]))

Thanks.

Advertisement

Answer

edit — I’ve updated for new version of networkx. In general, please look at the Migration Guide for how to update your code from networkx 1.11 to 2.x.

I think you are asking for how to find how many edges a node has. This is known as the degree of a node.

For networkx v2.x, G.degree(node ) gives you the dgree of the node and G.degree() is a ‘DegreeView’ object. It can be converted into a dict using dict(G.degree()).

G = nx.Graph()
G.add_edges_from([[1,2],[1,3],[2,4],[2,5]])
G.degree()
> DegreeView({1: 2, 2: 3, 3: 1, 4: 1, 5: 1})
max(dict(G.degree()).items(), key = lambda x : x[1])
> (2,3)

in networkx v1.11 and lower: G.degree(node) gives you the degree of the node and G.degree() is a dict whose keys are the nodes and whose values are the corresponding degrees.

So max(G.degree().items(), key = lambda x: x[1]) is a simple one-liner that returns (node, degree) for the node with maximum degree.

Here is an example:

G = nx.Graph()
G.add_edges_from([[1,2],[1,3],[2,4],[2,5]])
G.degree()
> {1: 2, 2: 3, 3: 1, 4: 1, 5: 1}
max(G.degree().items(), key = lambda x: x[1])
> (2,3)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement