You can download this code by clicking the button below.
This code is now available for download.
This function performs a random walk on the given graph for a specified number of steps. It starts at a random node in the graph, then randomly selects a neighboring node and moves to it, repeating this process until the specified number of steps is reached.
Technology Stack : Igraph
Code Type : Graph Traversal
Code Difficulty : Intermediate
def random_walk_graph(graph, steps):
"""
Perform a random walk on the given graph for a specified number of steps.
:param graph: An igraph.Graph object representing the network.
:param steps: The number of steps to take in the random walk.
:return: A list of nodes visited during the random walk.
"""
visited = set()
current_node = graph.vcount() # Start at a random node
visited.add(current_node)
for _ in range(steps):
neighbors = list(graph.neighbors(current_node))
if not neighbors: # If no neighbors, break the loop
break
next_node = neighbors[int(len(neighbors) * random.random())] # Randomly select a neighbor
visited.add(next_node)
current_node = next_node
return list(visited)