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) # 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) # 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. # 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") # 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...' # 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!