{
  "id": 18487448,
  "title": "Simulating the Two-Heads-in-a-Row Puzzle in 20 Lines of Python",
  "url": "https://urgent.news/2026/11/06/simulating-the-two-heads-in-a-row-puzzle-in-20-lines-of-python",
  "topic": "tech",
  "section": "Tech",
  "published": "2026-11-06T11:07:27.000Z",
  "source": {
    "name": "Dev.to",
    "slug": "dev-to",
    "url": "https://dev.to/astraquant/simulating-the-two-heads-in-a-row-puzzle-in-20-lines-of-python-309f"
  },
  "original_language": "en",
  "account": "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.",
  "summary": "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…",
  "key_points": [
    "Simulation confirms expected 6 flips for two consecutive heads",
    "Python code defines function to track coin flip streaks",
    "Streak resets to 0 after tails, lengthening wait time"
  ],
  "editors_take": null,
  "illustration": null,
  "coverage": {
    "outlets": 1,
    "also_reported_by": []
  },
  "ai_generated": true,
  "disclaimer": "Summaries, key points and the editor’s take are written by software from other outlets’ reporting and may contain errors — always check the linked original."
}