From 77421729682c691637e95fe8a1b410f61f59b008 Mon Sep 17 00:00:00 2001 From: neingeist Date: Fri, 19 Jun 2015 22:23:59 +0200 Subject: [PATCH] add hth --- hth.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 hth.py diff --git a/hth.py b/hth.py new file mode 100644 index 0000000..fb07b5b --- /dev/null +++ b/hth.py @@ -0,0 +1,27 @@ +#!/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))