Reputation: 1234
I am able to add an edge between any two individual node like below:
G.add_edge(node1, node)
But if I wanted to and edge between any two nodes (All nodes should be adjacent to each other) it becomes difficult when large number of nodes are taken.
Example:
If number are nodes are four and they are 1,2,3,4.The Graph should look like this
For above graph I am adding nodes as follow:
graph = [(1, 2),(1, 3),(1, 4), (2, 3),(2, 4), (3, 4)]
for edge in graph:
G.add_edge(edge[0], edge[1])
Is there any default option as parameter in Graph construction for my requirement?
Basically I need to construct a clique for given nodes.
Thanks
Upvotes: 3
Views: 4024
Reputation: 23897
From your description I think you're trying to make a complete graph. Networkx has a built in method to create a complete graph.
import networkx as nx
G=nx.complete_graph(4)
G.edges()
>[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
If you don't want the nodes to be named 0,1,2,3
, then you can rename the nodes in G
with some other names. Follow the commands above with:
nodenames = ['a', 'b', 'c', 'd']
mapping = {i:nodename for i,nodename in enumerate(nodenames)}
#now mapping looks like {0:'a', 1:'b', ...}
H=nx.relabel_nodes(G,mapping)
H.edges()
> [('a', 'c'), ('a', 'b'), ('a', 'd'), ('c', 'b'), ('c', 'd'), ('b', 'd')]
(note - I'm not a fan of the dict comprehension I used to define mapping
- I'd appreciate if anyone can give me a more direct version that doesn't require enumerating).
Upvotes: 4