import random # Programmer: Sriram Pemmaraju # Date: Feb 10, 2012 # Version 3: moves the person at random, one step at a time, left or right, # until the person reaches a barrier n or -n. Outputs the number of steps # it took to reach the barrier # This function takes in the value of the barrier, simulates a random # walk that terminates on reaching the barrier, and returns the length # of the simulated random walk def randomWalk(n): location = 0 # tracks the person's current location length = 0 # tracks the length of the random walk # This moves the person until she reaches the barrier at n or -n while abs(location) != n: step = random.randint(0, 1) # returns 0 or 1, each with prob. 1/2 # Adjusts the random number to be either -1 or +1 if step == 0: step = -1 location = location + step # updates location length = length + 1 return length # This is the main part of the program (i.e., outside the function) n = input("Enter the value of the barrier (a positive integer): ") sum = 0 # track the total length of all simulated random walks counter = 0 while counter < 100: sum = sum + randomWalk(n) counter = counter + 1 print float(sum)/100