You can download this code by clicking the button below.
This code is now available for download.
Generate a random walk path and calculate the total distance and average distance.
Technology Stack : random, math, statistics, string, re, json, html, datetime, hashlib, locale, sys, os, shutil
Code Type : Function
Code Difficulty : Intermediate
def random_walk(n):
import random
import math
import statistics
import string
import re
import json
import html
import datetime
import hashlib
import locale
import sys
import os
import shutil
if not isinstance(n, int) or n <= 0:
raise ValueError("The number of steps must be a positive integer")
steps = [(random.choice([1, -1]), random.choice([1, -1])) for _ in range(n)]
total_distance = sum(math.hypot(x, y) for x, y in steps)
average_distance = statistics.mean(steps, key=lambda point: math.hypot(*point))
return total_distance, average_distance