如何使用python / igraph在图中找到两个随机未连接的节点?

时间:2016-06-24 09:11:31

标签: python igraph

按照我之前关于在图中找到两个未连接节点及其接受的响应(How to find two randoms nodes with no edges between them in graph?)的问题。我想在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函数。但它返回两个节点之间的多个边缘或自循环!有谁知道解决方案?

1 个答案:

答案 0 :(得分:0)

这个怎么样:

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