计算 NetworkX 图的断开组件的数量

dat*_*ess 4 python graph-theory networkx

从随机生成的树开始,我想考虑树的每个节点,并可能以一定的概率删除它p。由于树没有循环,并且任何一对节点之间都有唯一的路径,因此删除节点应该会留下d断开的树,其中d是该节点的度。

我的问题是,一旦我对整个图表执行了此操作,我如何检查有多少个未连接的段?

import networkx as nx
import random as rand

n = 20
p = 0.1

G = nx.random_tree(n)
for i in range(0, n):
    if rand.random() < p:
        G.remove_node(i)

x = G.count_disconnected_components() # is there anything that accomplishes this?
Run Code Online (Sandbox Code Playgroud)

例如,对于此图,G.count_disconnected_components()应返回 3。 具有三个未连接组件的图

fel*_*iks 5

在我看来,你实际上想计算连接部分的数量。尝试number_connected_components

print(list(nx.connected_components(G)))
print(nx.number_connected_components(G))
Run Code Online (Sandbox Code Playgroud)