Harvard:Biophysics 101/2007/Notebook:Xiaodi Wu/2007-2-8

From OpenWetWare

Jump to: navigation, search

The script:

#!/usr/bin/env python

from random import *

# Generate random strings and tally
print "generating randomness...please wait one moment..."
tally_H = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
tally_T = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

for i in range(10000):
  # Generate a string
  a = ''.join([choice('HT') for n in range(10)])
  
  # Do a tally
  for i in range(10):
    # Generate search strings
    substr_H = ''.join(['H' for n in range(i+1)])
    substr_T = ''.join(['T' for n in range(i+1)])
    
    # Do the actual searching
    pos_H = a.find(substr_H, 0)
    while not pos_H == -1:
      tally_H[i] = tally_H[i] + 1
      pos_H = a.find(substr_H, pos_H+1)
    
    pos_T = a.find(substr_T, 0)
    while not pos_T == -1:
      tally_T[i] = tally_T[i] + 1
      pos_T = a.find(substr_T, pos_T+1)

# Print tally
print "and the tally for contiguous heads or tails is:\n"

for i, v in enumerate(tally_H):
  print ''.join(['H' for n in range(i+1)]).rjust(12),
  print v

print ''

for i, v in enumerate(tally_T):
  print ''.join(['T' for n in range(i+1)]).rjust(12),
  print v

print ''

# Print summed up results
print "and the summed up results are:\n"

def add(x, y): return x + y
tally = map(add, tally_H, tally_T)

for i, v in enumerate(tally):
  print str(i+1).rjust(11) + ':',
  print v
  
print ''

print '-' * 40
print "Xiaodi Wu, Biophysics 101, 2007-02-08\n"

...and the output...

generating randomness...please wait one moment...
and the tally for contiguous heads or tails is:

           H 49809
          HH 22358
         HHH 9879
        HHHH 4291
       HHHHH 1836
      HHHHHH 762
     HHHHHHH 290
    HHHHHHHH 106
   HHHHHHHHH 33
  HHHHHHHHHH 8

           T 50191
          TT 22704
         TTT 10114
        TTTT 4424
       TTTTT 1880
      TTTTTT 774
     TTTTTTT 301
    TTTTTTTT 101
   TTTTTTTTT 32
  TTTTTTTTTT 5

and the summed up results are:

          1: 100000
          2: 45062
          3: 19993
          4: 8715
          5: 3716
          6: 1536
          7: 591
          8: 207
          9: 65
         10: 13

----------------------------------------
Xiaodi Wu, Biophysics 101, 2007-02-08

Personal tools