Problem "HHT against HTT" (Python)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This programme tests the "HHT and HTT" probability problem
# by Xilin SUN
# Problem: A fair coin is tossed consecutively. Once the sequence
# "HHT" appears, person A wins and the game is terminated. Once the
# sequence "HTT" appears, person B wins and the game is also terminated.
# Find the probability that person A wins.
# The solution to this problem is not very straightforward, but by
# no means difficult to find. I am not going to paste the solution
# here. The answer should be 2/3. Below is a program to verify such
# answer.
from random import randint
CaseHHT = 0
CaseHTT = 0
NumberofCases = 500000
print "Doing a test with " + str(NumberofCases) +" cases."
for i in range (1,NumberofCases):
digit1=randint(0,1)
digit2=randint(0,1)
digit3=randint(0,1)
while True:
if digit1 == 0 and digit2 == 0 and digit3 == 1:
CaseHHT +=1
# print "Number of cases when 'HHT' wins = " + str(CaseHHT)
break
elif digit1 == 0 and digit2 == 1 and digit3 == 1:
CaseHTT +=1
# print "Number of cases when 'HTT' wins = " + str(CaseHTT)
break
else:
digit1=digit2
digit2=digit3
digit3=randint(0,1)
else:
print "Number of cases when 'HHT' wins = " + str(CaseHHT)
print "Number of cases when 'HTT' wins = " + str(CaseHTT)
print "Probability of 'HHT' winning = " + str(100*CaseHHT/float(NumberofCases)) + "%"