Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Coin Flip Problem
import random
def flips_coin():
# Flips a coin: returns H or T
choices = list('HT')
random.shuffle(choices)
return random.choice(choices)
def flips_until_hits(target):
target = list(target)
flips = []
while True:
result = flips_coin()
flips.append(result)
last_two_flips = flips[-2:]
if len(flips) > 1 and last_two_flips == target:
return flips
# Test Cases
HT_flipper_flips = []
HH_flipper_flips = []
#import pdb; pdb.set_trace()
# Run 10000 tests
for n in range(10000):
HT_flipper_flips.append(len(flips_until_hits('HT')))
HH_flipper_flips.append(len(flips_until_hits('HH')))
print('HT flipper AVG: %.2f' % (sum(HT_flipper_flips) / len(HT_flipper_flips)))
print('HH flipper AVG: %.2f' % (sum(HH_flipper_flips) / len(HH_flipper_flips)))

From a comment by aws17576 on MetaFilter:

By the way, I wholeheartedly endorse Persi Diaconis's comment that probability is one area where even experts can easily be fooled. This was demonstrated to me in grad school when my advisor, addressing a roomful of mathematicians, posed this problem:

Person A flips a coin repeatedly, stopping the first time two heads in a row appear. Person B flips a coin repeatedly, stopping the first time a head and then a tail appear in a row. Who will flip the coin more times on average -- A, B, or is there no difference?

He let everyone think for a moment, then took a show of hands. Almost everyone got it wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.