whiletrue
whiletrue

Reputation: 11105

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.

Upvotes: 4

Views: 2002

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210982

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

Upvotes: 4

Related Questions