Fair-Coin Streaks and Bayesian Bias Updating
Hard · Statistics & Math · Data Scientist · Online Assessment
Problem Statement
Implement solve_coin_question(question: int) -> object to compute exact analytical answers to three independent coin-flipping probability and inference sub-problems selected by question:
def solve_coin_question(question: int) -> object:
-
Competing three-flip sequences (
question == 1): An unbiased coin (P(H) = P(T) = 0.5) is flipped independently over and over until either the contiguous pattern"HHH"or the contiguous pattern"THH"appears. Return as afloatthe exact probability that"HHH"occurs before"THH". -
Expected maximum head streak (
question == 2): An unbiased coin is flipped15independent times. LetLbe the length of the longest contiguous streak of"H"outcomes across those15flips (L = 0when all15flips land"T"). ReturnE[L]as an exactfloat. -
Posterior bias distribution (
question == 3): A coin lands heads with unknown probabilitythetain[0, 1], whose prior density on[0, 1]is proportional totheta^3. Suppose4independent flips of this coin all land heads. Return a dictionary describing the exact normalized posterior distribution ofthetawith four keys:"family":"Beta""alpha": integer first shape parameter (int)"beta": integer second shape parameter (int)"density": normalized density expression string"<constant> * theta^<alpha-1> * (1 - theta)^<beta-1> for 0 <= theta <= 1", omitting any factor whose exponent is0and omitting^1when an exponent is1.
For any question value other than 1, 2, or 3, raise ValueError.
Examples
The miniature companion cases below illustrate the exact rules and return formats without revealing the numerical answers for question = 1, 2, 3:
Example 1
Companion race ("HH" before "TH" on a fair coin):
Opening flips "HH" (probability 1/4) -> "HH" completes immediately.
Opening flip "T..." (probability 3/4 across non-"HH" starts) -> once any "T" has landed,
the very first "H" afterward completes "TH" before "HH" can ever form.
Exact probability = 0.25 (returned as float by solve_coin_question(1) for "HHH" vs "THH")
Whenever one pattern's suffix overlaps the other pattern's prefix, the race can be far from 0.5 even though isolated windows have equal probability.
Example 2
Companion streak expectation (3 fair coin flips, 8 equally likely outcomes):
L = 0: {TTT} -> 1 outcome
L = 1: {HTT, THT, TTH, HTH} -> 4 outcomes
L = 2: {HHT, THH} -> 2 outcomes
L = 3: {HHH} -> 1 outcome
Exact expectation = (0*1 + 1*4 + 2*2 + 3*1) / 8 = 1.375
(solve_coin_question(2) returns the corresponding float for 15 fair flips)
Summing exact rational probabilities avoids Monte Carlo sampling noise.
Example 3
Companion Bayesian update (prior density proportional to theta on [0, 1], 2 flips both heads):
Prior theta^1 = theta^(2 - 1) * (1 - theta)^(1 - 1) -> Beta(alpha=2, beta=1)
Likelihood of 2 heads = theta^2 -> posterior proportional to theta^3
Normalized posterior dictionary:
{
"family": "Beta",
"alpha": 4,
"beta": 1,
"density": "4 * theta^3 for 0 <= theta <= 1"
}
(solve_coin_question(3) returns this dictionary schema for prior theta^3 and 4 heads;
solve_coin_question(0) raises ValueError)
Because beta - 1 == 0, (1 - theta)^0 equals 1 and is omitted from "density", while the constant 4 ensures the density integrates to 1 over [0, 1].
Constraints
- Valid selector values are
questionin{1, 2, 3}; all other integer inputs must raiseValueError. - Floating-point results for
question == 1andquestion == 2are checked within1e-6relative/absolute tolerance, so random Monte Carlo trials without exact arithmetic are too noisy. - Standard library only (
fractions,math, etc.).
Step-by-step walkthrough
Understand the three sub-problems and exactness requirements
solve_coin_question(question)answers three probability and statistics puzzles depending onquestion:question == 1: Repeatedly flip a fair coin. ReturnP(HHH appears before THH)as afloat.question == 2: Flip a fair coin 15 times. ReturnE[longest consecutive run of heads]as afloat.question == 3: Given a coin biasthetaon[0, 1]with prior density proportional totheta^3and 4 flips that all land heads, return the posterior distribution as a dictionary:{"family": "Beta", "alpha": 8, "beta": 1, "density": "8 * theta^7 for 0 <= theta <= 1"}.
Notice why random Monte Carlo simulation is not sufficient here: even 1,000,000 simulated games leave random sampling noise around
0.001, whereas the judge checks floating-point answers to1e-6. By solving each part with exactFractionarithmetic and converting tofloatonly on the final line, we eliminate simulation noise completely.Question 1 logic: why THH traps every late HHH
At first glance,
HHHandTHHeach have probability(1/2)^3 = 1/8on any isolated block of 3 tosses, tempting people to guess1/2. That guess fails because the end ofTHH(HH) is the start ofHHH.Suppose
HHHappears for the very first time at tosses(k, k + 1, k + 2):Case A: k = 1 (first three tosses are H, H, H) Tosses: H H H --> No 'T' has ever appeared, so THH is impossible. HHH wins! Probability = (1/2) * (1/2) * (1/2) = 1/8 = 0.125 Case B: k > 1 (HHH finishes after toss 3, so toss k - 1 exists) Toss index: k-1 k k+1 k+2 Must be: T H H H \_________/ THH already finished at toss k+1 (one toss BEFORE HHH)!Why must toss
k - 1beTin Case B? Because if tossk - 1wereH, then tosses(k - 1, k, k + 1)would already beHHH, contradicting that tossk + 2was the first timeHHHfinished! Therefore, the only wayHHHever beatsTHHis on the very first three flips, giving1/8 = 0.125.Question 1 code: state-machine probability propagation
In an interview, give the 4-line proof above first. In code, we can verify it with a reusable state machine that works on any pair of patterns (
firstvssecond):- Only the last
max(len(first), len(second)) - 1flips can contribute to an unfinished pattern (2flips for length-3 patterns). - We maintain
active_states, mapping each undecided recent suffix to its exactFractionprobability, starting from{"": Fraction(1)}. - Each flip splits every active state's probability in half (
+'H'and+'T'), adding mass that completesfirstintofirst_wins, discarding mass that completessecond, and merging the remaining branches by their new suffix.
Toss 0: { "": 1 } Toss 1: { "H": 1/2, "T": 1/2 } Toss 2: { "HH": 1/4, "HT": 1/4, "TH": 1/4, "TT": 1/4 } Toss 3: "HH"+H -> "HHH" (first_wins += 1/8!) "TH"+H -> "THH" (second wins 1/8, discarded) Remaining active_states: { "HT": 2/8, "TH": 2/8, "TT": 2/8 } (Notice "HH" is gone forever: reaching "HH" from "TH" completes "THH" first!)def pattern_race(first: str, second: str, tolerance: float = 1e-15) -> float: """Return P(`first` appears before `second`) when tossing a fair coin.""" # Only the last (max_pattern_len - 1) tosses can form part of an unfinished pattern. suffix_len = max(len(first), len(second)) - 1 # active_states: maps recent toss suffix (str) -> exact probability (Fraction), # e.g. {'HT': Fraction(1, 4), 'TH': Fraction(1, 4), 'TT': Fraction(1, 4)} active_states: Dict[str, Fraction] = {"": Fraction(1)} first_wins = Fraction(0) # Advance one fair toss at a time until remaining undecided probability <= tolerance. while sum(active_states.values()) > tolerance: next_states: Dict[str, Fraction] = {} for history_suffix, state_prob in active_states.items(): branch_prob = state_prob / 2 for coin_face in ("H", "T"): extended = history_suffix + coin_face if extended.endswith(first): first_wins += branch_prob elif extended.endswith(second): # `second` appeared first on this branch, so discard its mass. continue else: # Guard suffix_len == 0 because extended[-0:] would keep the whole string. if suffix_len == 0: next_state = "" else: next_state = extended[-suffix_len:] next_states[next_state] = next_states.get(next_state, Fraction(0)) + branch_prob active_states = next_states return float(first_wins)- Only the last
Question 2 idea: the tail-sum formula and bounded-run DP
Enumerating all
2^ncoin sequences takesO(n * 2^n)time — fast enough forn = 15(32,768sequences), but impossible forn = 100. Instead, we combine two clean ideas that run inO(n^3)integer operations:- The tail-sum formula for expected value. Let
Lbe the longest run of heads (0 <= L <= n). NormallyE[L] = 1*P(L = 1) + 2*P(L = 2) + 3*P(L = 3) + .... Look what happens if we writekcopies ofP(L = k)vertically and sum by rows instead of columns:
Row k = 1: P(L=1) + P(L=2) + P(L=3) + ... + P(L=n) = P(L >= 1) Row k = 2: P(L=2) + P(L=3) + ... + P(L=n) = P(L >= 2) Row k = 3: P(L=3) + ... + P(L=n) = P(L >= 3) ... ------------------------------------------------------------------ Col sums: 1*P(L=1) + 2*P(L=2) + 3*P(L=3) + ... = E[L]So
E[L] = sum_{k=1..n} P(L >= k). And sinceL >= kis the exact opposite ofL <= k - 1, we only need a helper that counts sequences whose longest head streak never exceedsmax_allowed_run = k - 1!- Dynamic programming by current trailing streak. Build a valid sequence flip by flip. At any point, the only thing we need to know to enforce
max_run <= max_allowed_runon future flips isr, how many consecutive'H's sit at the very end right now (0 <= r <= max_allowed_run):- Appending
'T'resets any streak back to0, sonext_ways[0] = sum(ways_by_trailing_heads). - Appending
'H'moves streakrtor + 1for0 <= r < max_allowed_run, while sequences already atr == max_allowed_runare dropped so they never reachmax_allowed_run + 1!
- Appending
- The tail-sum formula for expected value. Let
Question 2 code and 4-toss hand trace
Let's write both functions and verify them on
n = 4(2^4 = 16sequences) before runningn = 15:def count_sequences_with_max_run_at_most(num_tosses: int, max_allowed_run: int) -> int: """Count length-`num_tosses` H/T sequences whose longest H-streak is <= `max_allowed_run`.""" # ways_by_trailing_heads[r]: valid prefixes built so far ending in r consecutive 'H's, # for 0 <= r <= max_allowed_run. ways_by_trailing_heads = [0] * (max_allowed_run + 1) ways_by_trailing_heads[0] = 1 for _ in range(num_tosses): next_ways = [0] * (max_allowed_run + 1) # Flipping 'T' resets any trailing 'H' streak back to 0. next_ways[0] = sum(ways_by_trailing_heads) # Flipping 'H' extends r heads to r + 1 heads; r == max_allowed_run is dropped # because extending it would create (max_allowed_run + 1) consecutive heads. for streak_len in range(max_allowed_run): next_ways[streak_len + 1] = ways_by_trailing_heads[streak_len] ways_by_trailing_heads = next_ways return sum(ways_by_trailing_heads) def expected_longest_run(num_tosses: int) -> float: """Compute E[longest consecutive run of heads] in `num_tosses` fair coin flips.""" total_sequences = 2 ** num_tosses expected = Fraction(0) # Tail-sum identity for whole numbers: E[L] = sum_{k=1..n} P(L >= k), # where P(L >= k) = 1 - P(L <= k - 1). for k in range(1, num_tosses + 1): at_most_k_minus_1 = count_sequences_with_max_run_at_most(num_tosses, k - 1) at_least_k = total_sequences - at_most_k_minus_1 expected += Fraction(at_least_k, total_sequences) return float(expected)Check
n = 3(Example 2) by hand and compare withn = 15:Hand check for n = 3 (8 total sequences, matching Example 2): k = 1: max_run <= 0 is {TTT} (1 seq) -> P(L >= 1) = (8 - 1)/8 = 7/8 k = 2: max_run <= 1 has no 'HH' (5 seqs) -> P(L >= 2) = (8 - 5)/8 = 3/8 k = 3: max_run <= 2 drops only HHH (7 seqs) -> P(L >= 3) = (8 - 7)/8 = 1/8 Sum E[L] = (7 + 3 + 1) / 8 = 11 / 8 = 1.375 For n = 15 (32,768 total sequences): Numerators of P(L >= k) for k = 1..15: 32767 + 31171 + 22159 + 12199 + 5984 + 2798 + 1279 + 576 + 256 + 112 + 48 + 20 + 8 + 3 + 1 = 109381 E[L] = 109381 / 32768 = 3.338043212890625Question 3 idea: Bayes' rule and conjugate Beta priors
Let
theta(between0and1) be the coin's unknown probability of landing heads.- Prior belief: Before flipping, our belief about
thetahas density proportional totheta^3. Compare that with the standard Beta distributionBeta(alpha, beta), whose density on[0, 1]is proportional to:theta^(alpha - 1) * (1 - theta)^(beta - 1)Matching exponents givesalpha - 1 = 3(soalpha = 4) andbeta - 1 = 0(sobeta = 1). Thus the prior isBeta(4, 1)! - Likelihood of the data: Since flips are independent given
theta, the probability of seeing 4 heads in 4 tosses istheta * theta * theta * theta = theta^4. - Bayes' rule (
posterior proportional to prior * likelihood):
Unnormalized posterior: p(theta | HHHH) proportional to theta^3 * theta^4 = theta^7 (prior) (4 heads) Match exponents with theta^(alpha - 1) * (1 - theta)^(beta - 1): alpha - 1 = 7 --> alpha = 8 beta - 1 = 0 --> beta = 1 (this is Beta(8, 1)!) Normalize so total area on [0, 1] equals 1: integral from 0 to 1 of theta^7 d(theta) = [theta^8 / 8] from 0 to 1 = 1/8 Divide by 1/8 --> p(theta | HHHH) = 8 * theta^7 for 0 <= theta <= 1Because a Beta prior multiplied by coin-flip likelihood always stays a Beta distribution (
alphagains#heads,betagains#tails), the Beta family is called the conjugate prior for coin flips.- Prior belief: Before flipping, our belief about
Question 3 code: exact Beta posterior dictionary
For any whole-number parameters
alpha >= 1andbeta >= 1, calculus tells us the normalizing constant1 / B(alpha, beta)equals(alpha + beta - 1)! / ((alpha - 1)! * (beta - 1)!). Let's verify onalpha = 8, beta = 1:(8 + 1 - 1)! / (7! * 0!) = 8! / 7! = 8.We format the
densitystring carefully to match the required output schema ("8 * theta^7 for 0 <= theta <= 1"), omitting any power-zero factor like(1 - theta)^0:def beta_posterior(prior_alpha: int, prior_beta: int, heads: int, tails: int) -> Dict[str, Any]: """Update a Beta(prior_alpha, prior_beta) prior after seeing `heads` H and `tails` T.""" # Conjugate Beta-Binomial update: heads add to alpha, tails add to beta. alpha = prior_alpha + heads beta = prior_beta + tails # For positive integers, 1 / B(alpha, beta) = (alpha + beta - 1)! / ((alpha - 1)! (beta - 1)!). normalizer = factorial(alpha + beta - 1) // (factorial(alpha - 1) * factorial(beta - 1)) factors = [str(normalizer)] if alpha - 1 == 1: factors.append("theta") elif alpha - 1 > 1: factors.append(f"theta^{alpha - 1}") if beta - 1 == 1: factors.append("(1 - theta)") elif beta - 1 > 1: factors.append(f"(1 - theta)^{beta - 1}") density = " * ".join(factors) + " for 0 <= theta <= 1" return { "family": "Beta", "alpha": alpha, "beta": beta, "density": density, }Complete solution
Putting all three parts together behind
solve_coin_question:from typing import Any, Dict, List, Optional, Set, Tuple from fractions import Fraction from math import factorial def pattern_race(first: str, second: str, tolerance: float = 1e-15) -> float: """Return P(`first` appears before `second`) when tossing a fair coin.""" # Only the last (max_pattern_len - 1) tosses can form part of an unfinished pattern. suffix_len = max(len(first), len(second)) - 1 # active_states: maps recent toss suffix (str) -> exact probability (Fraction), # e.g. {'HT': Fraction(1, 4), 'TH': Fraction(1, 4), 'TT': Fraction(1, 4)} active_states: Dict[str, Fraction] = {"": Fraction(1)} first_wins = Fraction(0) # Advance one fair toss at a time until remaining undecided probability <= tolerance. while sum(active_states.values()) > tolerance: next_states: Dict[str, Fraction] = {} for history_suffix, state_prob in active_states.items(): branch_prob = state_prob / 2 for coin_face in ("H", "T"): extended = history_suffix + coin_face if extended.endswith(first): first_wins += branch_prob elif extended.endswith(second): # `second` appeared first on this branch, so discard its mass. continue else: # Guard suffix_len == 0 because extended[-0:] would keep the whole string. if suffix_len == 0: next_state = "" else: next_state = extended[-suffix_len:] next_states[next_state] = next_states.get(next_state, Fraction(0)) + branch_prob active_states = next_states return float(first_wins) def count_sequences_with_max_run_at_most(num_tosses: int, max_allowed_run: int) -> int: """Count length-`num_tosses` H/T sequences whose longest H-streak is <= `max_allowed_run`.""" # ways_by_trailing_heads[r]: valid prefixes built so far ending in r consecutive 'H's, # for 0 <= r <= max_allowed_run. ways_by_trailing_heads = [0] * (max_allowed_run + 1) ways_by_trailing_heads[0] = 1 for _ in range(num_tosses): next_ways = [0] * (max_allowed_run + 1) # Flipping 'T' resets any trailing 'H' streak back to 0. next_ways[0] = sum(ways_by_trailing_heads) # Flipping 'H' extends r heads to r + 1 heads; r == max_allowed_run is dropped # because extending it would create (max_allowed_run + 1) consecutive heads. for streak_len in range(max_allowed_run): next_ways[streak_len + 1] = ways_by_trailing_heads[streak_len] ways_by_trailing_heads = next_ways return sum(ways_by_trailing_heads) def expected_longest_run(num_tosses: int) -> float: """Compute E[longest consecutive run of heads] in `num_tosses` fair coin flips.""" total_sequences = 2 ** num_tosses expected = Fraction(0) # Tail-sum identity for whole numbers: E[L] = sum_{k=1..n} P(L >= k), # where P(L >= k) = 1 - P(L <= k - 1). for k in range(1, num_tosses + 1): at_most_k_minus_1 = count_sequences_with_max_run_at_most(num_tosses, k - 1) at_least_k = total_sequences - at_most_k_minus_1 expected += Fraction(at_least_k, total_sequences) return float(expected) def beta_posterior(prior_alpha: int, prior_beta: int, heads: int, tails: int) -> Dict[str, Any]: """Update a Beta(prior_alpha, prior_beta) prior after seeing `heads` H and `tails` T.""" # Conjugate Beta-Binomial update: heads add to alpha, tails add to beta. alpha = prior_alpha + heads beta = prior_beta + tails # For positive integers, 1 / B(alpha, beta) = (alpha + beta - 1)! / ((alpha - 1)! (beta - 1)!). normalizer = factorial(alpha + beta - 1) // (factorial(alpha - 1) * factorial(beta - 1)) factors = [str(normalizer)] if alpha - 1 == 1: factors.append("theta") elif alpha - 1 > 1: factors.append(f"theta^{alpha - 1}") if beta - 1 == 1: factors.append("(1 - theta)") elif beta - 1 > 1: factors.append(f"(1 - theta)^{beta - 1}") density = " * ".join(factors) + " for 0 <= theta <= 1" return { "family": "Beta", "alpha": alpha, "beta": beta, "density": density, } def solve_coin_question(question: int) -> object: if question == 1: return pattern_race("HHH", "THH") if question == 2: return expected_longest_run(15) if question == 3: # Prior p(theta) proportional to theta^3 = theta^(4 - 1) * (1 - theta)^(1 - 1) # is Beta(alpha=4, beta=1); observing 4 heads adds 4 to alpha and 0 to beta. return beta_posterior(prior_alpha=4, prior_beta=1, heads=4, tails=0) raise ValueError(f"unknown question number: {question}")✅ Submit now — all tests should pass.
Intuition & how it works
Each of the three questions rewards looking at the structure of transitions rather than brute-forcing individual flip histories:
- Pattern race (
HHHbeforeTHH): ImagineTHHas a mandatory tollbooth sitting right beforeHHH's highway exit. The only way to reachHHHwithout driving throughTHHfirst is to start at the exit on your very first three flips (H, H, H, probability1/8). The moment even oneTlands, any future streak of heads must spellT -> TH -> THHone flip before it could ever spellHHH! In code, we verify this with a Markov state machine (a model that remembers only the last few flips needed to detect a pattern, rather than the entire flip history). - Expected longest head streak in 15 flips: Instead of scanning all
2^15flip strings, we use dynamic programming (solving a counting problem step by step by grouping sequences that share the same current state — here, the number of consecutive'H's at the end) alongside the tail-sum formula (computing the average of a non-negative whole numberLby addingP(L >= 1) + P(L >= 2) + ... + P(L >= n)). - Bayesian coin inference: Think of a Beta distribution
Beta(alpha, beta)(a continuous probability curve on[0, 1]proportional totheta^(alpha - 1) * (1 - theta)^(beta - 1)) as a running tally ofalphavirtual heads andbetavirtual tails. Because it is a conjugate prior (a prior family whose updated posterior distribution after seeing data stays in the exact same family), Bayes' rule (updating prior density by multiplying by the probability of the observed data and re-normalizing to area1) simply adds the4observed heads toalpha!
Why do naive approaches fail? Guessing 0.5 for Question 1 ignores overlap: HHH and THH occur equally often over the long run, yet THH wins 7/8 of head-to-head races! Estimating Questions 1 and 2 via random.choice leaves sampling error around 10^-3 even after a million trials — far too coarse for a 10^-6 judge tolerance. And in Question 3, misreading theta^3 as alpha = 3 instead of alpha - 1 = 3 (alpha = 4) shifts the entire posterior off by one.
Here is how all three calculations work on our companion traces and target inputs:
Q1 (Companion HH vs TH -> 1/4; target HHH vs THH -> 1/8):
First 3 flips == HHH (prob 1/8) -> HHH wins immediately.
First 3 flips != HHH (prob 7/8) -> at least one 'T' exists before any 'HHH',
so 'THH' always finishes first -> P = 0.125.
Q2 (Longest head run on n = 3 flips from Example 2, 8 sequences):
P(L >= 1) = 7/8 (all except TTT)
P(L >= 2) = 3/8 (HHT, THH, HHH)
P(L >= 3) = 1/8 (HHH)
E[L] = 7/8 + 3/8 + 1/8 = 11/8 = 1.375 (for n = 15: 109381 / 32768 = 3.338043212890625)
Q3 (Companion theta^1 + 2 heads -> Beta(4,1); target theta^3 + 4 heads -> Beta(8,1)):
Prior: theta^3 = Beta(4, 1) --> +4 heads, +0 tails --> Posterior: Beta(8, 1)
Normalize theta^7 on [0, 1]: integral is 1/8, so density = 8 * theta^7.
Complexity
- Question 1 (
pattern_race): Letmbe the maximum pattern length (m = 3here). At most2^(m - 1)suffixes (4suffixes form = 3) can be active at once, so each simulated flip inspectsO(2^(m - 1))states and checks string suffixes inO(m)time. Reaching1e-15undecided probability takesO(log(1 / tolerance))flips (165iterations forHHHvsTHH), usingO(2^(m - 1))space. (Using the closed-form proof(1/2)^3 = 1/8takesO(1)time andO(1)space.) - Question 2 (
expected_longest_run): Fornflips (n = 15),count_sequences_with_max_run_at_most(n, limit)runsniterations over an array of lengthlimit + 1, costingO(n * limit)arithmetic operations. Calling it forlimit = 0, 1, ..., n - 1totalsO(n^3)integer operations (only a few thousand steps forn = 15, versusO(n * 2^n)for full enumeration) andO(n)space for theways_by_trailing_headslist. - Question 3 (
beta_posterior):O(alpha + beta)arithmetic steps to compute three small integer factorials (8!at largest here) andO(1)space.
Edge cases
- Question 1, non-trivial pattern pairs:
HHHvsTHHis decided by toss 3 becauseTHHends withHH, but other pairs such asHTHvsHHT(P = 1/3) can run arbitrarily long;pattern_racehandles both. - Question 1, short history and length-1 patterns: On toss 1 (
"H"),extended[-2:]safely returns"H"; whensuffix_len == 0(length-1 patterns), we explicitly return""because Python treats-0as0(extended[0:]would keep the entire string instead of clearing it). - Question 2, boundary
k = 1(max_allowed_run = 0): Only the all-tails sequenceTT...T(1sequence) has zero heads, soP(L >= 1) = (2^n - 1) / 2^n. - Question 2, exact binary denominator: Because every sequence of
15fair flips has probability1 / 32768,E[L] = 109381 / 32768is an exact binary fraction representable with zero rounding loss in IEEE-754float. - Question 3,
beta == 1(beta - 1 == 0): Since(1 - theta)^0 = 1, that factor is omitted from the formatted density string ("8 * theta^7 for 0 <= theta <= 1"). Similarly, an exponent of1formats cleanly without^1. - Question 3, unnormalized prior input: The statement writes
p(theta) proportional to theta^3without its prior normalizing constant4. Because Bayes' rule re-normalizes at the end, multiplying or omitting constants in the prior never changes the posterior.
Common mistakes
- Answering
0.5for Question 1 ("Penney's game" trap): Even thoughE[flips until HHH] = 14andHHHandTHHeach have probability1/8at any fixed 3-flip window, head-to-head races depend on how one pattern's suffix overlaps the other's prefix. - Using Monte Carlo random trials for Questions 1 or 2: Standard error shrinks only as
1 / sqrt(trials), requiring roughly10^12simulated games to guarantee1e-6accuracy. - Off-by-one errors in the tail-sum loop: Starting
kat0addsP(L >= 0) = 1extra unit to the expectation; usingcount_sequences_with_max_run_at_most(n, k)instead of(n, k - 1)computes1 - P(L <= k) = P(L > k)and missesP(L >= 1). - Reading
theta^3asBeta(3, 1)instead ofBeta(4, 1): InBeta(alpha, beta), the exponent onthetaisalpha - 1, notalpha. Starting fromalpha = 3yieldsBeta(7, 1)instead ofBeta(8, 1). - Forgetting the normalizing constant
8in Question 3:theta^7integrates to1/8on[0, 1], so a valid probability density function must multiply by8to integrate to1.
Follow-up questions
- How can you compute the head-to-head winning probability for any two fair-coin patterns directly without iterating toss by toss? Use Conway's leading-number algorithm! For any two patterns
AandB(neither inside the other), define the overlap scoreA : Bby checking each lengthk = 1..min(len(A), len(B)): whenever the lastkletters ofAequal the firstkletters ofB, add2^(k - 1). Then the exact odds thatBappears beforeAare(A : A - A : B)to(B : B - B : A). ForA = HHHandB = THH, we getA : A = 1 + 2 + 4 = 7,A : B = 0,B : B = 4, andB : A = 1 + 2 = 3, giving odds(7 - 0)to(4 - 3) = 7 : 1againstHHH, orP(HHH first) = 1/8. - As the number of fair coin flips
ngrows large, how does the expected longest consecutive run of heads scale? It grows logarithmically, roughly aslog2(n)(more precisely, oscillating tightly aroundlog2(n / 2) + gamma / ln(2) + 0.5, which is roughlylog2(n) - 0.6). Doubling the number of coin flips increases the expected longest streak by about1head (3.34atn = 15,4.29atn = 30,5.26atn = 60), which is why seeing a streak of 7 or 8 heads in 200 fair flips is completely normal rather than evidence of a rigged coin! - Under the
Beta(8, 1)posterior from part 3, what is the predictive probability that flip 5 lands heads, and how would observing tails update the distribution? The posterior predictive probability of heads on the next flip equals the mean ofthetaunder the posterior, which forBeta(alpha, beta)is simplyalpha / (alpha + beta) = 8 / (8 + 1) = 8/9(up from the prior mean4/5, and smoother than the naive maximum-likelihood estimate4/4 = 1). If that 5th toss landed tails,betawould increment by1toBeta(8, 2)with density72 * theta^7 * (1 - theta)and new mean8/10 = 0.8.
Follow-up questions
- How can you compute the head-to-head winning probability for any two fair-coin patterns directly without iterating toss by toss?
- As the number of fair coin flips `n` grows large, how does the expected longest consecutive run of heads scale?
- Under the `Beta(8, 1)` posterior from part 3, what is the predictive probability that flip 5 lands heads, and how would observing tails update the distribution?
Similar questions
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips
- Statistical Inference and Sizing for Trip Cancellations
- Impact of Dataset Duplication on OLS and Large-Sample Inference
- Three-Dice Product Distribution and Quoting Risk