You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
28 lines
615 B
Python
28 lines
615 B
Python
10 years ago
|
#!/usr/bin/python
|
||
|
from random import choice, seed
|
||
|
|
||
|
def ht():
|
||
|
"""Toss a coin and return H or T."""
|
||
|
return choice(["H", "T"])
|
||
|
|
||
|
def numberoftosses(pattern):
|
||
|
"""Return the number of tosses until we hit the pattern."""
|
||
|
s = len(pattern) * ht()
|
||
|
while s[-len(pattern):] != pattern:
|
||
|
s += ht()
|
||
|
|
||
|
return(len(s))
|
||
|
|
||
|
def avgnumberoftosses(pattern, tries = 10000):
|
||
|
"""Return the average number of tosses until we hit the pattern."""
|
||
|
n = 0.0
|
||
|
for t in range(tries):
|
||
|
n += numberoftosses(pattern)
|
||
|
n /= tries
|
||
|
|
||
|
return n
|
||
|
|
||
|
seed()
|
||
|
for pattern in "HTH", "HTT":
|
||
|
print pattern, round(avgnumberoftosses(pattern))
|