Random Walk on Graphs with Python

  • Share this:

Code introduction


This function performs a random walk on a given graph, starting from a specified node and walking for a specified number of steps.


Technology Stack : The package and technology stack used in the code

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_walk(graph, start_node, steps=10):
    """
    Perform a random walk on a graph starting from a given node and walk for a specified number of steps.
    """
    import igraph as ig
    import random

    # Check if the graph is directed or undirected
    is_directed = graph.is_directed()

    # Initialize the current node
    current_node = start_node

    # Initialize the path with the starting node
    path = [current_node]

    # Perform the random walk
    for _ in range(steps):
        neighbors = graph.neighbors(current_node)
        if neighbors:  # Ensure there are neighbors to walk to
            next_node = random.choice(neighbors)
            path.append(next_node)
            current_node = next_node
        else:
            break

    return path