# RW1.py # Charles VanLoan # Feb 27, 2015 """ Illustrates a 1-dimensional random walk """ from random import randint as randi def RandomWalk(n): """ Returns the number of steps required by a robot hopping along the x-axis to get more than n units away from the origin. PreC: n is a positive integer """ # The robot starts at x=0 x = 0 steps = 0 while abs(x)<=n: r = randi(1,2) if r==1: # Robot hops one unit to the right x = x+1 else: # Robot hops one unit to the left. x = x-1 steps = steps+1 return steps # Application Script if __name__ == '__main__': """ Perform 10 simulations and report on how long it takes the robot to get n units away from the origin. """ n = 100 for k in range(10): print '%6d' % RandomWalk(n)