Simulating Random Walks and Counting Final Positions

  • Share this:

Code introduction


This code simulates 1000 random random walks and calculates the deviation from the starting position. It uses the random library to generate random numbers, the itertools library to generate a list of paths, and the collections.Counter to count the occurrence of each final position.


Technology Stack : random, itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_walk(n):
    import random
    import itertools
    from collections import Counter

    def walk():
        x, y = 0, 0
        for _ in range(n):
            direction = random.choice(['N', 'E', 'S', 'W'])
            if direction == 'N':
                y += 1
            elif direction == 'E':
                x += 1
            elif direction == 'S':
                y -= 1
            elif direction == 'W':
                x -= 1
        return x, y

    paths = [walk() for _ in range(1000)]
    return Counter(paths)