I need to generate a fully connected subgraph with networkx, starting from the list of nodes I want to connect. Basically, I want all the nodes in the list I pass to the function to be all connected with each other.
I wonder if there is any built-in function to achieve this (which I haven't found)? Or should I think of some algorithm?
Thank you very much.
There is a function for creating fully connected (i.e. complete) graphs, nameley
complete_graph
.It takes an integer argument (the number of nodes in the graph) and thus you cannot control the node labels. I haven't found a function for doing that automatically, but with
itertools
it's easy enough:combinations(nodes, 2)
will create 2-element tuples with all pair combinations ofnodes
which then will work as the edges in the graph.This solution is however only valid for undirected graphs. Take a look at zubinmehta's solution for a more general approach.
You can use the networkx commands to directly generate a clique with integer nodes, and then there is a simple command to relabel the nodes with any other hashable names.
I don't know of any method which does this, but you can easily mimic the complete_graph() method of networkx and slightly change it(almost like a builtin):