Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically connect all nodes with all the other nodes in networkx

Assuming I have created a MultiDiGraph in networkx as follows:

G = nx.MultiDiGraph()
for i in range(5):
   G.add_node(i, features=...)

So the resulting graph might look like this:

Is there a way to now connect all nodes with all the other nodes (except self-edges) without specifying each target and source node manually?

I'm aware of the function nx.complete_graph() but I wonder whether there's a way to first create the nodes and then assign the connections in an automatic way.

like image 299
whiletrue Avatar asked Sep 16 '25 03:09

whiletrue


1 Answers

If I understand correctly:

from itertools import product

G.add_edges_from((a,b) for a,b in product(range(5), range(5)) if a != b)

drawing

pos = nx.circular_layout(G)
nx.draw(G, pos, with_labels=True, arrows=True, node_size=700)

enter image description here

like image 121
MaxU - stop WAR against UA Avatar answered Sep 17 '25 19:09

MaxU - stop WAR against UA