【问题标题】:How to find two random unconnected nodes in graph using python/igraph?如何使用 python/igraph 在图中找到两个随机未连接的节点?
【发布时间】:2016-07-11 04:41:24
【问题描述】:

按照我之前关于在图中查找两个未连接节点及其接受的响应 (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 函数。但它会返回两个节点或自循环之间的多条边!有谁知道解决方案?

【问题讨论】:

    标签: python igraph


    【解决方案1】:

    这个怎么样:

    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
    

    【讨论】:

    • 感谢您的回复,但此函数还会返回自循环和节点之间的多重边!
    • 如果您不想要自循环,只需将u != v 添加到if 条件。我不确定你所说的多重边缘是什么意思;当然,如果您多次调用get_random_unconnected_node_pair(),则可能会多次返回相同的(u, v) 对;您可以在调用get_random_unconnected_node_pair() 之前在两个节点之间添加一条边以避免这种情况,或者将get_random_unconnected_node_pair() 的结果存储在列表中,然后将其转换为set
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多