Maryam
Maryam

Reputation: 33

How to find two random unconnected nodes in graph using python/igraph?

Following my previous question on finding two unconnected nodes in graph and its accepted response (How to find two randoms nodes with no edges between them in graph?). I want to do the same in python/igraph. I want to use this code for making a graph or finding two unconnected nodes in a graph then add one edge between them. I wrote the function in 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

I tried both G.es.select and G.neighbors functions. But it returns back multiple edges between two nodes or self-loop! Does anyone knows the solution?

Upvotes: 0

Views: 533

Answers (1)

Tamás
Tamás

Reputation: 48051

How about this:

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

Upvotes: 1

Related Questions