How do I get the giant component of a NetworkX gra

2019-01-24 11:57发布

问题:

I don't know if NetworkX recently tweaked one of the methods to be a generator instead of returning a list, but I'm looking for a good (rather, better) way to get the GC of a graph.

I have a working, but really inefficient-looking, snippet down:

# G = nx.Graph()
giant = sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[0]

Is there a cleaner way?

回答1:

In networkx 1.9, connected_components_subgraphs returns an iterator (instead of a sorted list). The values yielded by the iterator are not in sorted order. So to find the largest, use max:

giant = max(nx.connected_component_subgraphs(G), key=len)

Sorting is O(n log n). Taking the max is O(n).