如何在图形中找到它们之间没有边缘的两个random节点?

时间:2016-05-12 10:09:28

标签: python networkx

我在python中很新,我想在网络中找到两个没有边缘的随机节点,但我的程序有时会返回空列表或两个以上的节点。 任何人都可以帮助我,我的计划是:

import networkx as nx
import random
n=6  
m=10
G=nx.gnm_random_graph( n, m, seed=None, directed=True)
result = []
nodes = random.sample(G.nodes(), 2)
for u in nodes:
    for v in nodes:
        if u != v and G.has_edge(u,v) is False and G.has_edge(v,u) is  False:
        result.append((u,v))
    else:
        nodes = random.sample(G.nodes(), 2)
 print(result)

2 个答案:

答案 0 :(得分:2)

如果您只想要一对节点,则没有理由制作列表。找到那对!

while True:
    u, v = random.sample(G.nodes(), 2)
    if not (G.has_edge(u, v) or G.has_edge(v, u)):
        break

现在直接使用uv

答案 1 :(得分:0)

import networkx as nx
import random
n=6  
m=10
G=nx.gnm_random_graph( n, m, seed=None, directed=True)
nodes = G.nodes()

def select_2_random_unconnected_nodes(node_list, graph):

    selected_node = random.choice(node_list)

    # obtain all the nodes connected to the selected node
    connected_nodes = [n for _, n in G.edges(selected_node)]

    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_nodes + [selected_node]]

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

    return selected_node, select_second_node