You can download this code by clicking the button below.
This code is now available for download.
Generate a random walk path, starting from a point and randomly moving in one of the four directions.
Technology Stack : random, itertools
Code Type : Function
Code Difficulty : Beginner
def random_walk(num_steps):
import random
import itertools
def move(position):
direction = random.choice(['N', 'E', 'S', 'W'])
if direction == 'N':
return (position[0], position[1] + 1)
elif direction == 'E':
return (position[0] + 1, position[1])
elif direction == 'S':
return (position[0], position[1] - 1)
else:
return (position[0] - 1, position[1])
path = [move((0, 0)) for _ in range(num_steps)]
return path