簡體   English   中英

如何在圖中找到兩個無邊的隨機節點?

[英]How to find two randoms nodes with no edges between them in graph?

我是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)

如果只需要一對節點,則無需列出列表。 只要找到那對!

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

現在直接使用uv

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

暫無
暫無

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

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