如何从未连接的图中随机选择两个节点(节点对),Python,networkx [英] how to select two nodes (pairs of nodes) randomly from a graph that are NOT connected, Python, networkx

查看:385
本文介绍了如何从未连接的图中随机选择两个节点(节点对),Python,networkx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从图中提取两个节点,发现它们不应该连接,即它们之间不存在直接边.我知道我可以使用"random.choice(g.edges())"获得随机边缘,但这会给我连接的随机节点.我想要未连接的节点对(一对未连接的边).帮帮我...谢谢

I want to extract two nodes from a graph, the catch being that they shouldnt be connected i.e. no direct edge exists between them. i know i can get random edges using "random.choice(g.edges())" but this would give me random nodes that are connected. I want pairs of nodes that are NOT connected (a pair of unconnected edges). help me out guys...thanx

推荐答案

简单! :)

获取一个随机节点-然后从不包括邻居及其自身的节点列表中选择一个随机节点.下面说明的代码. :)

Grab a random node - then pick a random node from the list of nodes excluding neighbours and itself. Code to illustrate is below. :)

import networkx as nx
from random import choice

# Consider this graph
#
#     3
#     |
# 2 - 1 - 5 - 6
#     | 
#     4

g = nx.Graph()
g.add_edge(1,2)
g.add_edge(1,3)
g.add_edge(1,4)
g.add_edge(1,5)
g.add_edge(5,6)

first_node = choice(g.nodes())                  # pick a random node
possible_nodes = set(g.nodes())
neighbours = g.neighbors(first_node) + [first_node]
possible_nodes.difference_update(neighbours)    # remove the first node and all its neighbours from the candidates
second_node = choice(list(possible_nodes))      # pick second node      

print first_node, second_node

这篇关于如何从未连接的图中随机选择两个节点(节点对),Python,networkx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆