Harvard:Biophysics 101/2007/Notebook:Kaull/2007-2-8

From OpenWetWare
Jump to: navigation, search

Programming Assignment, due 2/8/07

Code:

#!/usr/bin/env python

##########
## Script "flips a coin" and tallies strings of heads/tails

#initialize useful variables
from random import choice

coin = ['H', 'T']

max_repeat = 10
num_trials = 10000
num_flips = 10

data = []

#generate coin flip data
for trial in range(num_trials):
    data.append(''.join([choice(coin) for n in range(num_flips)]))

#count contiguous overlapping repeats
#Method 2 from HW 2/06

for state in coin:  #heads or tails

    counts = [0 for n in range(max_repeat+1)]

    for i in range(2, max_repeat+1):
        #generate repeat sequences, length 2 to max
        substr = ''.join([state for n in range(i)])

        for trial in data:
            #loop through all trials
            pos = trial.find(substr, 0)
            while not pos == -1:
                counts[i] = counts[i]+1
                pos = trial.find(substr, pos+1)

        print substr, counts[i]
    print '\n'

Output:

HH 22346
HHH 9830
HHHH 4288
HHHHH 1802
HHHHHH 747
HHHHHHH 289
HHHHHHHH 96
HHHHHHHHH 25
HHHHHHHHHH 3


TT 22588
TTT 9977
TTTT 4358
TTTTT 1872
TTTTTT 775
TTTTTTT 296
TTTTTTTT 114
TTTTTTTTT 39
TTTTTTTTTT 10