Random Walk Path Generator

  • Share this:

Code introduction


This function generates a random walk path based on the specified number of steps and starting point.


Technology Stack : random (random number generation)

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_walk(n, start=(0, 0)):
    """
    生成一个随机的漫步路径,漫步次数为n。

    :param n: 漫步的次数
    :param start: 漫步的起始点,默认为(0, 0)
    :return: 一个包含漫步路径的列表
    """
    import random
    x, y = start
    path = [(x, y)]
    for i in range(1, n):
        dx = random.choice([-1, 1])
        dy = random.choice([-1, 1])
        x += dx
        y += dy
        path.append((x, y))
    return path