import random
def flip_a_fair_coin(N):
coin = ['H', 'T']
record = []
for i in range(N):
record.append(random.choice(coin))
# record is a list of H and T; turn it into a string by using string.join.
record = "".join(record)
return record
flip_a_fair_coin(5)
'HHTTT'
# count the number of times you see a "run" of a given pattern, e.g. HTTHHT, in a given pattern of coinflips
def count_runs(run, coinflips):
return coinflips.count(run)
flips = flip_a_fair_coin(10000)
the_count = count_runs('HTHHTT', flips)
# expected:
p = 1.0/2**6 # length of the 'HTHHTT' string, above
expected_count = p * len(flips)
print 'expected', expected_count, '; got:', the_count, '; diff: ', abs(the_count - expected_count)
expected 156.25 ; got: 153 ; diff: 3.25
There are some strings -- hint, including some rather simple ones -- for which count_strings doesn't work properly: that is, the actual counts differ, sometimes dramatically, from the expected counts. Write down at least two examples 'runs' and develop a simple hypothesis as to what's going on, i.e. why count_runs is broken.
# CTB -- the main problem is this: 'count' does not count overlapping runs.
# so, for example:
print count_runs("HT", "HTHTHTHT")
# works fine, but:
print count_runs("HH", "HHHH")
# does not -- there should be THREE pairs of heads in there, but .count is only finding the one at position 0 and the one at position 2.
# So basically any runs that could contain overlaps don't work.
4 2
Write your own count_runs -- you can use 'string.find' in a loop, for example -- that works properly. Verify that it works on the above strings.
# There are a couple different ways to do this. Perhaps the easiest is this:
def count_runs2(run, coinflips):
the_count = 0
for n in range(len(coinflips)):
if coinflips[n:n + len(run)] == run:
the_count += 1
return the_count
print count_runs2("HH", "HHHH")
3
# One important point for everyone -- string.find doesn't work the way you think it does!
s = "HH"
if s.find("HH"):
print 'Found it!'
else:
print 'Didn\'t find it...'
Didn't find it...
# this is because string.find returns -1 when it *doesn't* find the string... and that evaluates to True in an if statement.
# REMEMBER: ALWAYS TEST YOUR CODE WITH SOMETHING SIMPLE TO SEE IF IT'S WORKING!