Can You Time The Stoplight Just Right?

A FiveThirtyEight Riddler puzzle.

By Vamshi Jandhyala in mathematics Riddler

January 20, 2017

Riddler Express

You and I find ourselves indoors one rainy afternoon, with nothing but some loose change in the couch cushions to entertain us. We decide that we’ll take turns flipping a coin, and that the winner will be whoever flips 10 heads first. The winner gets to keep all the change in the couch! Predictably, an enormous argument erupts: We both want to be the one to go first.

What is the first flipper’s advantage? In other words, what percentage of the time does the first flipper win this game?

Solution

from random import random

def flip():
    return 1 if random() > 0.5 else 0

runs = 100000

nfw = 0
for _ in range(runs):
    nah, nbh = 0, 0
    while(True):
        if flip():
            nah += 1
        if nah == 10:
            nfw += 1
            break
        if flip():
            nbh += 1
        if nbh == 10:
            break
print("Percentage of first person wins: ", nfw/runs)