Setup
Let's assume the following undirected graph:
import networkx as nx
G = nx.from_edgelist([(0, 3), (0, 1), (2, 5), (0, 3)])
G.add_nodes_from(range(7))
or even adding the (1, 3) edge (it doesn't matter here):
The connected components are:
list(nx.connected_components(G))
# [{0, 1, 3}, {2, 5}, {4}, {6}]
Question
Is it possible to generate the graph G
from the list of connected components directly with networkx
? Or using a simple method?
The only solution I found so far is to generate the successive edges or all combinations of nodes per group and feed it to nx.from_edgelist
, then to add the single nodes with add_nodes_from
:
from itertools import pairwise, chain
l = [{0, 1, 3}, {2, 5}, {4}, {6}]
G = nx.from_edgelist(chain.from_iterable(pairwise(e) for e in l))
G.add_nodes_from(set.union(*l))
or for all edges:
from itertools import combinations, chain
l = [{0, 1, 3}, {2, 5}, {4}, {6}]
G = nx.from_edgelist(chain.from_iterable(combinations(e, 2) for e in l))
G.add_nodes_from(set.union(*l))
permutations
. Usecombinations
. There are exactly twice as many elements inpermutations(cc, 2)
as incombinations(cc, 2)
, and those are all redundant elements if G is a simple undirected graph. – Calzadacombinations
andpermutations
give different graphs? My point is precisely that they would give the exact same graph, butcombinations
is more efficient. – CalzadaG = nx.from_edgelist(chain.from_iterable(list(combinations(e, 2)) for e in l))
is equivalent toG = nx.from_edgelist(chain(combinations(cc, 2) for cc in l))
. You don't need to build alist( )
then use.from_iterable
. – Calzadanetworkx
can do this natively. (NB. you were right on the edgelist btw, I hadn't checked) – Baxterpairwise
:from itertools import pairwise; G = nx.from_edgelist(pairwise(cc) for cc in l)
. Then you have a number of edges which is linear instead of quadratic. – Calzadapairwise
/combination
notcombinations
/permutations
), but again, not the question ;) – Baxternetworkx
answer – BaxterG = nx.union_all(nx.path_graph(cc) for cc in l)
(equivalent to using pairwise) orG = nx.union_all(nx.complete_graph(cc) for cc in l)
(equivalent to using combinations) – Calzadamap
). Thanks! (don't hesitate if you want to post as answer). Would you know an equivalent for all combinations of edges? – Baxter