簡體   English   中英

如何使用python / igraph在圖中找到兩個隨機的未連接節點?

[英]How to find two random unconnected nodes in graph using python/igraph?

遵循我之前關於在圖中找到兩個未連接節點及其接受的響應的問題( 如何在圖中找到兩個在它們之間沒有邊的隨機節點? )。 我想在python / igraph中做同樣的事情。 我想使用此代碼制作圖形或在圖形中找到兩個未連接的節點,然后在它們之間添加一條邊。 我在python / igraph def select_2_random_unconnected_nodes(node_list,G)中編寫了該函數:

selected_node = random.choice(node_list)

# obtain all the nodes connected to the selected node
connected_nodes1 = [n for _, n in G.es.select(_source=selected_node)]
connected_nodes2 = [n for _, n in G.es.select(_target=selected_node)]
#connected_nodes1 = [n for n in G.neighbors(selected_node, mode='out')]
#connected_nodes2 = [n for n in G.neighbors(selected_node, mode='in')]


#print(connected_nodes + [selected_node])

# a feasible node is one not in connected_nodes and also not the first selected_node
feasible_nodes = [feasible_n for feasible_n in node_list if feasible_n not in connected_nodes1 + connected_nodes2 + [selected_node]]

# select a second node from the feasible_nodes list
select_second_node = random.choice(feasible_nodes)

return selected_node, select_second_node

我嘗試了G.es.select和G.neighbors函數。 但是它返回兩個節點之間的多個邊或自循環! 有人知道解決方案嗎?

這個怎么樣:

from random import randint

def get_random_unconnected_node_pair(graph):
    n = graph.vcount() - 1
    while True:
        u = random.randint(0, n)
        v = random.randint(0, n)
        if not graph.are_connected(u, v):
            return u, v

暫無
暫無

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

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