You can download this code by clicking the button below.
This code is now available for download.
This function simulates a random walk in a two-dimensional space. Each step is randomly chosen to move left, right, up, or down, for a total of n steps. It returns the final coordinates.
Technology Stack : random, math
Code Type : Function
Code Difficulty : Intermediate
def random_walk(n):
import random
import math
def move():
return [random.choice([-1, 1]), random.choice([-1, 1])]
x, y = 0, 0
for _ in range(n):
x, y = x + move()[0], y + move()[1]
return x, y