簡體   English   中英

Python:查找連接到n的所有節點(元組)

[英]Python: Find all nodes connected to n (tuple)

我想確定我是否可以從某個節點訪問所有節點。 我對路徑不感興趣,如果可以或不能,我只想輸出YES或NO。 假設我有以下圖形-作為約束,我需要將我的節點表示為元組(i,j):

graph={
    (1,1): [(1,2),(2,2)]
    (1,2): [(1,3)]
    (1,3): [(1,2),(2,3)]
    (2,2): [(3,3)]
    (2,3): []
    (3,3): [(2,2)]
}

現在,我需要顯示我是否可以從(1,1),(2,2)或(3,3)到達,即(i,j)且i = j,其他所有節點,其中i!= j。 如果是,則打印(YES)-如果否,則打印(NO)。 由於我可以通過節點(1,1)到達(1,2),(1,3)和(2,3),因此上述示例將為節點(1,1)輸出是。

我嘗試使用以下

G = nx.DiGraph()
G.add_edges_from(graph)
for reachable_node in nx.dfs_postorder_nodes(G, source=None):
    print reachable_node

但是,如果我在nx.dfs_postorder.nodes()中將(1,1),(2,2)或(3,3)聲明為我的源,則會出現例如以下錯誤-> KeyError:(1,1)

我應該使用哪個函數或庫(庫越標准越好!)指示我是否可以從任何(i,i)節點訪問所有節點?

感謝您的所有澄清! 我是新成員,因此,如果我的問題不符合Stackoverflow准則,請隨時告訴我如何改善下一個問題!

該程序應該可以完成工作,並且它僅使用標准庫(基本上為您提供了在給定起點可以訪問的所有可能狀態):

graph={
    (1,1): [(1,2), (2,2)],
    (1,2): [(1,3)],
    (1,3): [(1,2), (2,3)],
    (2,2): [(3,3)],
    (2,3): [],
    (3,3): [(2,2)]
}

node0 = (1,1) #choose the starting node
node0_connections = [node0] #this list will contain all the possible states that can be visited from node0
for node in node0_connections: 
     for node_to in graph[node]:
         if  node0_connections.count(node_to) == 0:
             node0_connections.append(node_to)                
print 'All possible states to be visted from node', node0,':', node0_connections,'.'
count = node0_connections.count((1,2)) + node0_connections.count((1,3)) + node0_connections.count((2,2))
if count == 3:
    print 'YES'
else:
    print 'NO'

我想我理解你的問題。 您可以使用nx.shortest_path使用try/except塊嘗試詳盡的方法,如下所示:

import networkx as nx

graph={
    (1,1): [(1,2),(2,2)],
    (1,2): [(1,3)],
    (1,3): [(1,2),(2,3)],
    (2,2): [(3,3)],
    (3,3): [(2,2)],
    (4,4): [(1,3)],
    (5,5): []
}

G = nx.Graph(graph)
nodes = G.nodes()
balanced_nodes = [node for node in G.nodes() if node[0] == node[1]]
unbalanced_nodes = [node for node in G.nodes() if node[0] != node[1]]
for balanced_node in balanced_nodes:
    for unbalanced_node in unbalanced_nodes:
        connected = True
        try:
            path = nx.shortest_path(G,balanced_node, unbalanced_node)
        except:
            connected = False
            break
    print(balanced_node, ": ", connected)

結果是:

(1, 1) :  True
(2, 2) :  True
(3, 3) :  True
(4, 4) :  True
(5, 5) :  False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM