[Edu-sig] Simple Stats (curriculum fragment...)
kirby urner
kirby.urner at gmail.com
Wed May 27 06:15:37 CEST 2009
"""
Simple randomizer and tally machine.
Drop a ball 'howmany' times so it falls
left or right for 'howmany' rows of
pegs -- like Pachinko
http://www.4dsolutions.net/ocn/graphics/randtrianim.gif
(c) GPL, 4D OCN 2009
Python 3.0.1 (r301:69556, Mar 14 2009, 14:06:26)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
"""
from random import randint
def leftright():
"""
spit out L or R (left or right)
until the cows come home
"""
while True:
yield ['R','L'][randint(0,1)]
def the_fall(howfar):
"""
drop from the top: go left or right
for however far
"""
mypath = []
for i in range(howfar):
mypath.append(next(y)) # using da generator
return mypath
def many_falls(howmany, howfar):
"""
dropping the ball, building a dictionary (sample)
Order of Ls and Rs in a single fall leads to same
final position, so index by string e.g. LLLLRRR
"""
counters = {}
for i in range(howmany):
thepath = "".join((sorted(the_fall(howfar))))
counters[thepath] = counters.setdefault(thepath,0) + 1
return counters
def display(sample):
"""
spit out the fall strings in alpha order
with associated counts
"""
thekeys = sorted(sample.keys())
for i in thekeys:
print("%s : %4d" % (i, sample[i]))
def test():
"""
run a sample, display the results
"""
global y # so we can use it anywhere!
y = leftright()
sample = many_falls(10000, 10)
display(sample)
if __name__ == '__main__':
test()
==========
Multiple runs:
>>>
LLLLLLLLLL : 15
LLLLLLLLLR : 109
LLLLLLLLRR : 438
LLLLLLLRRR : 1205
LLLLLLRRRR : 1976
LLLLLRRRRR : 2491
LLLLRRRRRR : 2118
LLLRRRRRRR : 1138
LLRRRRRRRR : 416
LRRRRRRRRR : 84
RRRRRRRRRR : 10
>>>
LLLLLLLLLL : 11
LLLLLLLLLR : 96
LLLLLLLLRR : 454
LLLLLLLRRR : 1144
LLLLLLRRRR : 2027
LLLLLRRRRR : 2444
LLLLRRRRRR : 2066
LLLRRRRRRR : 1194
LLRRRRRRRR : 443
LRRRRRRRRR : 111
RRRRRRRRRR : 10
>>>
More information about the Edu-sig
mailing list