python - NetworkX largest component no longer working? -
according networkx documentation, connected_component_subgraphs(g) returns sorted list of components. first 1 should largest component.
however, when try largest component of graph g using example code on documentation page
g=nx.path_graph(4) g.add_edge(5,6) h=nx.connected_component_subgraphs(g)[0] i
typeerror: 'generator' object has no attribute '__getitem__' it used work on other computer earlier versions of networkx (1.7 think, not 100% sure)
now using different computer python 2.7.7 , networkx 1.9. version problem?
i have written small function couple lines myself find largest component, wondering why error came out.
btw, can components converting generator object list.
components = [comp comp in nx.connected_components(g)] but list not sorted component size stated in documentation.
example:
g = nx.graph() g.add_edges_from([(1,2),(1,3),(4,5)]) g.add_nodes_from(range(6,20)) components = [comp comp in nx.connected_components(g)] component_size = [len(comp) comp in components] print g.number_of_nodes(), g.number_of_edges(), component_size g = nx.graph() g.add_edges_from([(1000,2000),(1000,3000),(4000,5000)]) g.add_nodes_from(range(6,20)) components = [comp comp in nx.connected_components(g)] component_size = [len(comp) comp in components] print g.number_of_nodes(), g.number_of_edges(), component_size output:
19 3 [3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 19 3 [2, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] looks when node names large numbers , when there bunch of single nodes, returned subgraphs not sorted properly
the networkx-1.9 documentation here http://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.components.connected.connected_components.html#networkx.algorithms.components.connected.connected_components
the interface changed return generator (as figured out). example in documentation shows how ask.
generate sorted list of connected components, largest first.
>> g = nx.path_graph(4) >>> g.add_path([10, 11, 12]) >>> sorted(nx.connected_components(g), key = len, reverse=true) [[0, 1, 2, 3], [10, 11, 12]] or
>>> sorted(nx.connected_component_subgraphs(g), key = len, reverse=true)
Comments
Post a Comment