You can download this code by clicking the button below.
This code is now available for download.
This function implements a random walk on a given graph starting from a specified starting node and returns the path of the walk.
Technology Stack : Igraph, Random choice
Code Type : Algorithm implementation
Code Difficulty : Intermediate
def random_walk(graph, start_node, steps):
import igraph as ig
import random
if not isinstance(graph, ig.Graph):
raise ValueError("graph must be an instance of igraph.Graph")
walk = [start_node]
for _ in range(steps):
current_node = walk[-1]
neighbors = list(graph.neighbors(current_node))
if neighbors:
next_node = random.choice(neighbors)
else:
break
walk.append(next_node)
return walk