Simulating the Two-Heads-in-a-Row Puzzle in 20 Lines of Python
You flip a fair coin until you get two heads in a row. How many flips does it take, on average? Most people say 4. It feels right: two flips for HH would be 4 if you somehow "double" a 50/50 wait. The real answer is 6 . That gap between gut and math is why this puzzle is a favorite for learning expected value with states. Below is a tiny Monte Carlo simulation that estimates the answer, then a…
The "Two-Heads-in-a-Row" puzzle involves flipping a fair coin until two consecutive heads appear. Intuition might suggest the answer is 4, but the correct expected number of flips is 6. This simulation in Python confirms that result. The code defines a function `flips_until_two_heads()` that simulates the process and returns the number of flips needed.
It uses three states: 0 for no streak, 1 for one consecutive head, and 2 for the desired two heads in a row. The function updates a streak counter and resets it to 0 when tails appear. By running this simulation multiple times, the average number of flips converges to 6, matching the mathematically derived solution. The key insight is that streaks reset upon tails, making the wait longer than simply doubling a 50/50 wait.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.