self-avoiding random walk in python

Here's a Python implementation of a self-avoiding random walk algorithm:

main.py
import random

def generate_lattice(n):
    # generate an empty 2D lattice of size n x n
    lattice = [[0] * n for i in range(n)]
    # put a randomly chosen point in the middle of the lattice
    x, y = n//2, n//2
    lattice[x][y] = 1
    return lattice, x, y

def self_avoiding_random_walk(n, m):
    # generate the lattice and starting position
    lattice, x, y = generate_lattice(n)
    # perform m steps of the walk
    for step in range(m):
        # generate a list of valid directions to move in
        valid_directions = []
        if x > 0 and not lattice[x-1][y]:
            valid_directions.append((-1, 0))
        if x < n-1 and not lattice[x+1][y]:
            valid_directions.append((1, 0))
        if y > 0 and not lattice[x][y-1]:
            valid_directions.append((0, -1))
        if y < n-1 and not lattice[x][y+1]:
            valid_directions.append((0, 1))
        # if there are no valid directions to move, stop the walk early
        if not valid_directions:
            print(f"Stopped after {step} steps because there were no valid directions to move in.")
            return lattice
        # randomly choose a valid direction to move in
        dx, dy = random.choice(valid_directions)
        # move the walker to the new position and mark it as visited
        x, y = x+dx, y+dy
        lattice[x][y] = 1
    return lattice
1363 chars
36 lines

This implementation generates an empty lattice of size n x n and places a randomly chosen point in the middle of the lattice. It then performs m steps of the walk by generating a list of valid directions to move in (i.e. directions that do not result in the walker revisiting a previously-visited point) and randomly choosing one from that list. If there are no valid directions to move in, the walk stops early. The function returns the resulting lattice, which contains a path of m steps taken by the walker.

gistlibby LogSnag