Two-Dimensional Random Walk Simulation

  • Share this:

Code introduction


This function simulates a random walk in a two-dimensional plane with a specified number of steps. At each step, the function randomly chooses to move up, down, left, or right.


Technology Stack : random (built-in Python library used for generating random numbers)

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
def random_walk(n_steps):
    """
    Simulates a random walk with n_steps.
    """
    x, y = 0, 0
    for _ in range(n_steps):
        direction = random.choice(['up', 'down', 'left', 'right'])
        if direction == 'up':
            y += 1
        elif direction == 'down':
            y -= 1
        elif direction == 'left':
            x -= 1
        elif direction == 'right':
            x += 1
    return x, y