Random Walk Simulation in Python

  • Share this:

Code introduction


This function simulates a simple random walk process, starting from the origin (0,0), moving randomly up, down, left, or right n steps, and returning the final coordinates.


Technology Stack : random, math

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_walk(n):
    import random
    import math

    def move(x, y):
        direction = random.choice(['up', 'down', 'left', 'right'])
        if direction == 'up':
            return x + 1, y
        elif direction == 'down':
            return x - 1, y
        elif direction == 'left':
            return x, y - 1
        elif direction == 'right':
            return x, y + 1

    x, y = 0, 0
    for _ in range(n):
        x, y = move(x, y)
    return x, y                
              
Tags: