亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取包含一定數量節點的networkx子圖

獲取包含一定數量節點的networkx子圖

狐的傳說 2023-10-31 21:33:16
我有一個 networkx 有向圖,我想提取包含一定數量節點的子圖。例如,有向圖是 0-1-2-3-4-5。我想獲取所有包含3個節點的子圖。結果應該是:0-1-2、1-2-3、2-3-4、3-4-5。我怎樣才能做到這一點?
查看完整描述

1 回答

?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

我不完全確定我是否理解正確:你的例子意味著你只想要連接的子圖?在有向圖中,存在不止一種連接(弱連接和強連接)。因此,您必須決定要尋找哪一個。


這可能有效:


import networkx as nx

from itertools import combinations


# The graph in your example (as I understand it)

G = nx.DiGraph((i, i+1) for i in range(5))


num_of_nodes = 3 # Number of nodes in the subgraphs (here 3, as in your example)

subgraphs = [] # List for collecting the required subgraphs

for nodes in combinations(G.nodes, num_of_nodes):

    G_sub = G.subgraph(nodes) # Create subgraph induced by nodes

    # Check for weak connectivity

    if nx.is_weakly_connected(G_sub):

        subgraphs.append(G_sub)

combinations(G.nodes, num_of_nodes)迭代num_of_nodes來自 的許多節點的所有唯一組合G。


所選的子圖正是您提到的:


print([H.nodes for H in subgraphs])

print([H.edges for H in subgraphs])

節目


[NodeView((0, 1, 2)), NodeView((1, 2, 3)), NodeView((2, 3, 4)), NodeView((3, 4, 5))]

[OutEdgeView([(0, 1), (1, 2)]), OutEdgeView([(1, 2), (2, 3)]), OutEdgeView([(2, 3), (3, 4)]), OutEdgeView([(3, 4), (4, 5)])]

如果你的圖表是


G = nx.DiGraph([(i, i+1) for i in range(5)] + [(i+1, i) for i in range(5)])

如果您正在尋找強大的連接性,那么您必須使用


...

    # Check for strong connectivity

    if nx.is_strongly_connected(G_sub):

        ...

(通常的警告:G.subgraph()只給你一個視圖。)


查看完整回答
反對 回復 2023-10-31
  • 1 回答
  • 0 關注
  • 314 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號