You can download this code by clicking the button below.
This code is now available for download.
This function implements a simple random walk algorithm, simulating a person's path moving randomly in a two-dimensional space.
Technology Stack : random (random number generation), built-in data structures (list)
Code Type : Function
Code Difficulty : Intermediate
def random_walk(num_steps):
import random
x, y = 0, 0
directions = ['n', 's', 'e', 'w']
walk = [(x, y)]
for _ in range(num_steps):
direction = random.choice(directions)
if direction == 'n':
y += 1
elif direction == 's':
y -= 1
elif direction == 'e':
x += 1
elif direction == 'w':
x -= 1
walk.append((x, y))
return walk