'''
Created on Feb 13, 2011

@author: ola
'''
import random


def get_tosses(count):
    '''
    Toss simulated coin count (int) times
    Returns list of random coin tosses, 'T' or 'H'
    length of returned list is count
    '''
    tosses = []
    for i in range(0,count):
        if random.random() < 0.5:
            tosses.append("H")
        else:
            tosses.append("T")
    return tosses


def get_tosses2(count):
    tosses = ["T" if random.random() < 0.5 else "H" for i in range(0,count)]
    return tosses


def print_stats(tosses):
    '''
    Prints statistics for tosses, a list of
    coin tosses, each element of tosses either 'H' or 'T'
    '''
    tails = tosses.count("T")
    print "#tails = %d, # heads = %d" % (tails, len(tosses)-tails)
    runs = []
    rc = 0
    for toss in tosses:
        if toss == 'T':
            rc += 1
        else:
            if rc != 0:
                runs.append(rc)
            rc = 0
    runs.append(rc)
    maxt = max(runs)
    counts = [0]*(maxt+1)
    for t in runs:
        counts[t] += 1
    print "\nTail Runs"
    print "%s\t%s" % ("length", "count")
    for t in range(1,len(counts)):
        print "%3d\t%d" % (t,counts[t])



print_stats(get_tosses(10000))

'''
Output of one run shown below

#tails = 4995, # heads = 5005

Tail Runs
length    count
  1    1208
  2    656
  3    307
  4    152
  5    75
  6    35
  7    24
  8    10
  9    5
 10    2
 11    2
 12    1
 13    0
 14    1
'''
