You are on page 1of 1

Chapter 13.

Random Walks and More About Data Vizualization


The parameter dClass of simWalks is of type class, and is used in the first line of
code to create a Drunk of the appropriate subclass. Later, when drunk.takeStep
is invoked from Field.moveDrunk, the method from the appropriate subclass is
automatically selected.
The function drunkTest also has a parameter, dClass, of type class. It is used
twice, once in the call to simWalks and once in the first print statement. In the
print statement, the built-in class attribute __name__ is used to get a string
with the name of the class. The function drunkTest calculates the coefficient of
variation of the distance from the origin using the CV function defined in Figure
12.7.
def walk(f, d, numSteps):
"""Assumes: f a Field, d a Drunk in f, and numSteps an int >= 0.
Moves d numSteps times, and returns the difference between
the final location and the location at the start of the walk."""
start = f.getLoc(d)
for s in range(numSteps):
f.moveDrunk(d)
return start.distFrom(f.getLoc(d))
def simWalks(numSteps, numTrials, dClass):
"""Assumes numSteps an int >= 0, numTrials an int > 0,
dClass a subclass of Drunk
Simulates numTrials walks of numSteps steps each.
Returns a list of the final distances for each trial"""
Homer = dClass()
origin = Location(0.0, 0.0)
distances = []
for t in range(numTrials):
f = Field()
f.addDrunk(Homer, origin)
distances.append(walk(f, Homer, numTrials))
return distances
def drunkTest(walkLengths, numTrials, dClass):
"""Assumes walkLengths a sequence of ints >= 0
numTrials an int > 0, dClass a subclass of Drunk
For each number of steps in walkLengths, runs simWalks with
numTrials walks and prints results"""
for numSteps in walkLengths:
distances = simWalks(numSteps, numTrials, dClass)
print dClass.__name__, 'random walk of', numSteps, 'steps'
print ' Mean =', sum(distances)/len(distances),\
'CV =', CV(distances)
print ' Max =', max(distances), 'Min =', min(distances)

Figure 13.4 The drunkards walk (with a bug)

183

You might also like