Computer Programming 150
(April 10, 2008)
Lab 13a.py – Coin Tossing Simulation
#
# Name:
# File: Lab13a.py
# Date: April 10, 2008
#
# Desc : Simple Coin Tossing Simulation
#
from
random import randrange
from
myGraphics import drawList
class
Coin:
def __init__(self):
"
state of coin is either character H or T"
self.HTList =
["T", "H"]
self.value = self.HTList[randrange(0,2)]
def toss(self):
" toss
coin"
self.value = self.HTList[randrange(0,2)]
def getValue(self):
" return
state - either H or T "
return self.value
def __str__(self):
" implicit
call returns state as string"
if self.value
== "T":
return "Tails"
else:
return "Heads"
def
main():
# display title
print "Coin Toss Program"
# get number of coins to toss per trial
numTosses = input("\nEnter number of
times to toss a coin: ")
# ask before iterating loop
again = "y"
while (again == "y"):
# get number of trials to run
n = input("\nEnter number of Trials to run: ")
print
# initialize count array to all zeros
headCount =
[0]*(numTosses+1)
# create a coin object
c = Coin()
for i in range(n):
# execute one trial - count number of
heads
cnt = 0
for j in range(numTosses):
c.toss()
if c.getValue() ==
"H":
cnt
= cnt + 1
# increment count for that number of
heads
headCount[cnt] = headCount[cnt] + 1
# display table of results
print "Heads | Count"
for i in range(numTosses+1):
print " %2d %4d" % (i, headCount[i])
# graph distribution
drawList(headCount, "Frequency
Distribution")
# ask to go again
again = raw_input("\nAgain? (y/n): ")
main()
Lab13b.py – DNA Codon String Search
#
# Name:
# File: Lab13b.py
# Date: April 10, 2008
#
# Desc: DNA Codon Search
#
from
random import randrange
def
randString(n):
#
# returns a random string of G's A', T's
and C's
#
str =
""
charList =
["G", "A", "T", "C"]
for i in range(n):
str = str + charList[randrange(0,4)]
return str
def
main():
# display title
print "DNA Codon
Search"
# ask before iterating loop
again = "y"
while (again == "y"):
# generate a random string of length n
n = input("\nEnter Length of String: ")
str1 = randString(n)
print str1
print
# get search string (a.k.a. codon)
str2 = raw_input("Enter search
string: ")
n = len(str2)
indexList =
[]
# search for all occurrences of str2 in
str1
for i in range(len(str1)):
if str2 == str1[i:i+n]:
indexList.append(i)
# display results
if len(indexList)
== 0:
print str2, "not found"
else:
print str2, "found at", indexList
# go again?
again = raw_input("\nAgain? (y/n): ")
main()