You can download this code by clicking the button below.
This code is now available for download.
This function implements a random walk algorithm, starting from a specified starting node and performing a random walk for a specified number of steps in the graph.
Technology Stack : Graph-tool
Code Type : Graph algorithm
Code Difficulty : Intermediate
def random_walk(graph, start_node, steps=10):
import graph_tool as gt
# 初始化路径为起点
path = [start_node]
for _ in range(steps):
# 随机选择一个邻居节点
neighbors = graph.get_neighbors(path[-1])
if neighbors:
next_node = neighbors[gt.random_choice(len(neighbors))]
else:
break
path.append(next_node)
return path