Quantitative Probability and Combinatorics Toolkit
Hard · Software Engineering Fundamentals · Quantitative Trader · Online Assessment
Problem Statement
Implement a collection of exact discrete-mathematics, probability, expectation, Bayesian-inference, and logical-deduction functions using int and fractions.Fraction (so rational results never suffer floating-point rounding):
-
Combinatorial Counting
count_arrangements(word)— Return the number of distinct strings obtainable by permuting all characters ofword(""yields1).numbers_from_pairwise_sums(s1, s2, s3)— Given the three pairwise sumsx + y,x + z, andy + zof three unknown numbers, return[x, y, z]sorted in non-decreasing order asFractionvalues.count_rectangles(rows, cols)— Return how many axis-aligned rectangles (squares included) formed of whole unit cells exist inside arows × colsgrid.
-
Sampling Without Replacement
distinct_color_probabilities(counts, draws)— An urn holdscounts[i]indistinguishable tokens of categoryi. Sampledrawstokens uniformly without replacement and return{k: prob}mapping each achievable distinct-category countk(including only keys withprob > 0) to its exactFractionprobability. RaiseValueErrorifdraws < 0, any entry incountsis negative, ordraws > sum(counts).
-
Contest Wagering & Expected Net Profit
exact_order_bet_value(horses, places, cost, payout)— In a contest ofhorsesentrants whosehorses!finishing orders are equally likely, paying upfront feecostawards gross prizepayoutwhen your predicted 1st-through-places-th finishers match in exact sequence (and0otherwise). Return expected net profit (expected_gross_return - cost).horse_option_values()— For a 5-entrant uniform contest, return expected net profits for"a"through"e":"a","b","c", and"d"pay upfront fees10,20,30, and60to predict the exact top5,4,3, and2finishers respectively for gross prize1000, while"e"takes a guaranteedFraction(10)net profit without wagering.
-
Sequential Stopping & Accumulation
even_stop_probability(sides=2)— Roll an independent fairsides-faced die (1..sides) repeatedly until the newest roll matches the immediately preceding roll for the first time. Return the probability that the total roll count upon stopping is even. RaiseValueErrorifsides < 1.expected_flips_given_fewer(p_heads=Fraction(1, 2))— Two independent players each toss a biased coin (landing heads with probabilityp_heads) until seeing their own first heads. Conditioned on Player 1 finishing in strictly fewer tosses than Player 2, return Player 1's expected toss count. RaiseValueErrorunless0 < p_heads < 1.coupon_collector_cost(types, price)— Blind packs costpriceeach and independently yield one uniformly distributed design out oftypesdesigns. Return the expected total spend needed to collect alltypesdesigns (0whentypes == 0). RaiseValueErroriftypes < 0.reroll_expected_payout(sides=6, threshold=3)— Roll a fairsides-faced die (1..sides) and add the outcome to a running score; roll again whenever the latest face satisfiesface > threshold, stopping onceface <= threshold. Return the expected final score. RaiseValueErrorifsides < 1orthreshold < 1.
-
Bayesian Updating & Conditional Sampling
disease_given_positive(prevalence, sensitivity, false_positive_rate)— Given prior probabilityprevalence, true-positive ratesensitivity, andfalse_positive_rateamong unaffected individuals, return the posterior probability of having the condition given a positive test.box_posterior(boxes, draws, chosen)— One container is selected uniformly fromboxes, whereboxes[i] = (target_count, total_count). Samplingdrawsitems without replacement from that container yieldsdrawstarget items. Return the posterior probability thatboxes[chosen]was picked, raisingValueErrorif every container has zero probability of producing that observation.second_white_probability(total_balls)— An urn holdstotal_ballsitems, exactly half of which are white, and items are drawn without replacement. Given the first item drawn is white, return the exact probability that the second item is also white. RaiseValueErroriftotal_balls < 2ortotal_ballsis odd.
-
Uniform Dice & Arithmetic Triples
strictly_increasing_probability(dice=3, sides=6)— Rolldiceindependent fairsides-faced dice (1..sides) in sequence and return the probability that the recorded values are strictly ascending.leading_digit_one_probability(dice=3, sides=6)— Rolldiceindependent fairsides-faced dice (1..sides) and return the probability that the base-10 string of the product of all rolled faces starts with"1".average_triple_probability(n=30)— Choose 3 distinct integers uniformly without replacement from1..nand return the probability that one chosen integer equals the arithmetic mean of the other two. RaiseValueErrorifn < 3.
-
Speaker Role Deduction
consistent_role_assignments()andtrue_statement_count()— Four speakers at indices0, 1, 2, 3hold a permutation of("knight", "liar", "jester", "child")."knight"always makes a true claim;"liar"always makes a false claim;"jester"cannot stand at index0and speaks truthfully iff speakeri - 1spoke falsely;"child"cannot stand at index0and speaks truthfully iff speakeri - 1spoke truthfully. Claims by index:0claims"jester",1claims not"knight",2claims"knight", and3claims not"liar". Return all valid role 4-tuples inconsistent_role_assignments(), and return how many claims are true under the unique solution intrue_statement_count()(raisingValueErrorif not unique).
Examples
Example 1
Input:
count_arrangements("LEVEL")
numbers_from_pairwise_sums(14, 19, 23)
count_rectangles(3, 4)
distinct_color_probabilities([2, 3, 1], 2)
Output:
30
[Fraction(5, 1), Fraction(9, 1), Fraction(14, 1)]
60
{1: Fraction(4, 15), 2: Fraction(11, 15)}
Walk-through: "LEVEL" has 5! / (2! · 2! · 1!) = 30 distinct permutations. Adding 14 + 19 + 23 = 56 counts x + y + z twice (28), yielding [5, 9, 14]. A 3 × 4 grid has C(4, 2) · C(5, 2) = 6 · 10 = 60 rectangles. Out of C(6, 2) = 15 pairs from [2, 3, 1], 1 + 3 + 0 = 4 pairs share one category (4/15) and 11 use two (11/15).
Example 2
Input:
exact_order_bet_value(4, 2, 15, 120)
even_stop_probability(3)
expected_flips_given_fewer(Fraction(1, 3))
coupon_collector_cost(4, 6)
reroll_expected_payout(4, 2)
Output:
Fraction(-5, 1)
Fraction(3, 5)
Fraction(9, 5)
Fraction(50, 1)
Fraction(5, 1)
Walk-through: Naming top 2 of 4 wins with probability 1/12, so 120/12 - 15 = -5. A 3-sided die matches the prior roll with chance 1/3, giving (1/3) / (1 - 4/9) = 3/5 even-stop probability. With p_heads = 1/3, a synchronized round resolves with probability 1 - (2/3)^2 = 5/9, taking 9/5 rounds on average. Collecting 4 designs takes 1 + 4/3 + 2 + 4 = 25/3 packs (25/3 · 6 = 50). A 4-sided die with threshold = 2 averages 5/2 per roll and re-rolls half the time, yielding (5/2) / (1/2) = 5.
Example 3
Input:
disease_given_positive(Fraction(2, 100), Fraction(95, 100), Fraction(4, 100))
box_posterior([(10, 10), (4, 8), (0, 6)], 2, 0)
second_white_probability(10)
strictly_increasing_probability(2, 4)
leading_digit_one_probability(2, 4)
average_triple_probability(10)
true_statement_count()
Output:
Fraction(95, 291)
Fraction(14, 17)
Fraction(4, 9)
Fraction(3, 8)
Fraction(1, 4)
Fraction(1, 6)
3
Walk-through: Out of 10,000 people (200 affected), 190 are true positives and 392 are false positives (190/582 = 95/291). Container likelihoods for 2 target items are 1, 6/28 = 3/14, and 0, giving 1 / (17/14) = 14/17. After drawing 1 of 5 white items from 10, 4/9 remain white. Two 4-sided dice ascend in C(4, 2)/16 = 3/8 of outcomes and start with "1" on (1,1), (3,4), (4,3), (4,4) (4/16 = 1/4). In 1..10, C(5,2) + C(5,2) = 20 of C(10,3) = 120 triples (1/6) form an arithmetic progression, and the unique role assignment ("liar", "jester", "knight", "child") produces 3 true claims.
Constraints
- Return exact
intorfractions.Fractionobjects rather thanfloatapproximations. 0 <= len(word) <= 20;1 <= rows, cols <= 10^40 <= draws <= sum(counts) <= 30for validdistinct_color_probabilitiescalls1 <= places <= horses <= 151 <= dice <= 6and1 <= sides <= 10for explicit enumeration functions;n >= 3foraverage_triple_probability
Step-by-step walkthrough
Organize the toolkit around reusable probability patterns
Although the module spans combinatorics, urn draws, expected values, Bayesian inference, dice enumeration, and logic deduction, every function reduces to a small set of clean analytical ideas. Throughout
solution.py, we returnintorfractions.Fraction(exact numerator/denominator pairs likeFraction(4, 15)) so floating-point rounding never masks a reasoning slip.from typing import Dict, List, Tuple from fractions import Fraction import itertools import math # ROLES: fixed tuple of the four speaker roles in the deduction puzzle ROLES = ("knight", "liar", "jester", "child")Counting by symmetry and boundary lines
count_arrangements(word). Take"LEVEL"from Example 1:Lappears2times,Eappears2times, andVappears1time (5characters total). If identical letters carried tiny numbered tags (L1, L2andE1, E2), all5! = 120permutations would look distinct. Removing the tags collapses2!swaps of theLs and2!swaps of theEs into one string:5! / (2! * 2! * 1!) = 120 / (2 * 2 * 1) = 30numbers_from_pairwise_sums(s1, s2, s3). Trace(14, 19, 23)from Example 1. Instead of isolating one variable at a time, sum all three pairwise equations:(x + y) = 14 + (x + z) = 19 + (y + z) = 23 -------------- 2*(x + y + z) = 56 => x + y + z = 28Every unknown appears in exactly two pairs! Subtracting each pairwise sum from
28yields28 - 23 = 5,28 - 19 = 9, and28 - 14 = 14. UsingFraction(s1 + s2 + s3, 2)also handles odd totals such as(1, 1, 1) -> [1/2, 1/2, 1/2].count_rectangles(rows, cols). A grid of3rows by4columns (Example 1) is bounded by 4 horizontal lines (H0..H3) and 5 vertical lines (V0..V4):V0 V1 V2 V3 V4 H0 +----+----+----+----+ | | | | | H1 +----+----+----+----+ | | | | | H2 +----+----+----+----+ | | | | | H3 +----+----+----+----+Choosing any 2 horizontal lines (top and bottom edges) and any 2 vertical lines (left and right edges) uniquely frames one axis-aligned rectangle (including squares):
C(4, 2) * C(5, 2) = 6 * 10 = 60.def count_arrangements(word: str) -> int: """Problem 1: number of distinct orderings of the letters of word.""" # letter_counts: maps each character -> frequency, e.g. {'L': 2, 'E': 2, 'V': 1} letter_counts: Dict[str, int] = {} for letter in word: letter_counts[letter] = letter_counts.get(letter, 0) + 1 # Start with n! orderings as if identical letters wore distinct labels, # then divide out k! for each letter repeated k times (exact integer division). arrangements = math.factorial(len(word)) for count in letter_counts.values(): arrangements //= math.factorial(count) return arrangements def numbers_from_pairwise_sums(s1: int, s2: int, s3: int) -> List[Fraction]: """Problem 2: the three numbers whose pairwise sums are s1, s2, s3, sorted ascending.""" # Adding (x + y) + (x + z) + (y + z) counts every number twice: 2 * (x + y + z). # Using Fraction handles odd totals cleanly (e.g. sums 1, 1, 1 -> [1/2, 1/2, 1/2]). sum_of_all_three = Fraction(s1 + s2 + s3, 2) # Subtracting each pairwise sum leaves the single number omitted from that pair. first = sum_of_all_three - s1 second = sum_of_all_three - s2 third = sum_of_all_three - s3 return sorted([first, second, third]) def count_rectangles(rows: int, cols: int) -> int: """Problem 12: rectangles (squares included) made of whole cells of a rows x cols board.""" # A grid of `rows` cells high has `rows + 1` horizontal boundary lines (and `cols + 1` vertical). # Any 2 horizontal lines and any 2 vertical lines uniquely frame one axis-aligned rectangle. horizontal_line_pairs = math.comb(rows + 1, 2) vertical_line_pairs = math.comb(cols + 1, 2) return horizontal_line_pairs * vertical_line_pairsSampling tokens without replacement
Trace
counts = [2, 3, 1]withdraws = 2from Example 1 (6tokens in total). Labeling the tokens1..6givesC(6, 2) = 15equally likely 2-token subsets:- Single category (
k = 1):C(2, 2) + C(3, 2) + C(1, 2) = 1 + 3 + 0 = 4subsets ->4/15. - Two categories (
k = 2): pick one token from each of two categories (2*3 + 2*1 + 3*1 = 6 + 2 + 3 = 11subsets, or15 - 4 = 11) ->11/15.
In general, we enumerate every per-category draw vector
pickswith0 <= picks[i] <= min(counts[i], draws)whose entries sum todraws, multiplyC(available, picked)across categories, and accumulate counts by how many categories hadpicked > 0.def distinct_color_probabilities(counts: List[int], draws: int) -> Dict[int, Fraction]: """Problems 3-4: {k: P(exactly k distinct colors)} when drawing without replacement.""" if draws < 0 or any(count < 0 for count in counts): raise ValueError("counts and draws must be non-negative") total_items = sum(counts) total_ways = math.comb(total_items, draws) if total_ways == 0: raise ValueError("cannot draw more items than the bag holds") # per_color_ranges[i]: valid draw counts 0..min(counts[i], draws) from color i per_color_ranges = [range(min(count, draws) + 1) for count in counts] # ways_by_colors: maps distinct_color_count k -> total number of item subsets with k colors ways_by_colors: Dict[int, int] = {} for picks in itertools.product(*per_color_ranges): if sum(picks) != draws: continue # Multiply combinations across colors; since 0 <= picked <= count, ways_for_split >= 1, # which guarantees we only record color counts k that have strictly positive probability. ways_for_split = 1 distinct_colors = 0 for available, picked in zip(counts, picks): ways_for_split *= math.comb(available, picked) if picked > 0: distinct_colors += 1 ways_by_colors[distinct_colors] = ways_by_colors.get(distinct_colors, 0) + ways_for_split probabilities: Dict[int, Fraction] = {} for distinct_colors, ways in ways_by_colors.items(): probabilities[distinct_colors] = Fraction(ways, total_ways) return probabilities- Single category (
Contest wagers and expected net profit
With
horsesentrants and uniform finishing permutations, there areP(horses, places) = horses * (horses - 1) * ... * (horses - places + 1)equally likely ordered prefixes of lengthplaces. In Example 2 (horses = 4, places = 2, cost = 15, payout = 120),P(4, 2) = 12, so expected net profit is120 / 12 - 15 = -5.Evaluating
horse_option_values()across the 5-entrant contest (5! = 120):"a" (top 5, fee 10): 1000 / 120 - 10 = 25/3 - 10 = -5/3 "b" (top 4, fee 20): 1000 / 120 - 20 = 25/3 - 20 = -35/3 (top 4 fixes the 5th!) "c" (top 3, fee 30): 1000 / 60 - 30 = 50/3 - 30 = -40/3 "d" (top 2, fee 60): 1000 / 20 - 60 = 50 - 60 = -10 "e" (no wager): +10def exact_order_bet_value(horses: int, places: int, cost: int, payout: int) -> Fraction: """Problem 5: expected profit of paying `cost` to name the first `places` finishers in order.""" # Every ordered list of the top `places` finishers is equally likely: P(horses, places) outcomes. ordered_outcomes = math.perm(horses, places) expected_return = Fraction(payout, ordered_outcomes) return expected_return - cost def horse_option_values() -> Dict[str, Fraction]: """Problem 5: expected profit of each option "a".."e" ("e" = walk away with $10).""" return { "a": exact_order_bet_value(5, 5, 10, 1000), "b": exact_order_bet_value(5, 4, 20, 1000), "c": exact_order_bet_value(5, 3, 30, 1000), "d": exact_order_bet_value(5, 2, 60, 1000), "e": Fraction(10), }Stopping parity and synchronized coin races
even_stop_probability(sides). Roll 1 merely establishes the current face; it can never halt the process. From roll 2 onward, each roll independently matches the previous roll with probabilitym = 1/sides(stopping immediately) or misses withq = 1 - m. Stopping onn = 2, 4, 6, ...gives the geometric seriesm + q^2 * m + q^4 * m + ... = m / (1 - q^2). On Example 2 (sides = 3),m = 1/3andq = 2/3, yielding(1/3) / (1 - 4/9) = 3/5(and2/3whensides = 2).expected_flips_given_fewer(p_heads). Pair Player 1 and Player 2 in synchronized rounds1, 2, 3, ...(p = p_heads,q = 1 - p):Round outcome Probability Effect on the race ----------------------------------------------------------------------- (Tails, Tails) q * q Neither finished -> continue to next round (Heads, Tails) p * q Decisive round: Player 1 wins strictly (Tails, Heads) q * p Decisive round: Player 2 wins strictly (Heads, Heads) p * p Decisive round: TieRounds repeat only while both players flip tails (
q^2), so the index of the decisive round is geometric with success probability1 - q^2and mean1 / (1 - q^2). Because which decisive outcome ends the race is independent of how many(Tails, Tails)rounds preceded it, conditioning on(Heads, Tails)leaves the round distribution unchanged! Forp_heads = 1/3(Example 2),1 / (1 - 4/9) = 9/5(and4/3forp_heads = 1/2).def even_stop_probability(sides: int = 2) -> Fraction: """Problem 6: flip (or roll a fair `sides`-sided die) until two consecutive results are equal.""" if sides < 1: raise ValueError("need at least one side") # Flip 1 sets the initial value. From flip 2 onward, each flip matches the previous flip # with probability 1/sides. Stopping on n = 2, 4, 6, ... sums to match / (1 - miss^2). prob_match = Fraction(1, sides) prob_miss = 1 - prob_match return prob_match / (1 - prob_miss * prob_miss) def expected_flips_given_fewer(p_heads: Fraction = Fraction(1, 2)) -> Fraction: """Problem 13: E[Alice's flips | Alice needs fewer flips than Bob]; both flip until first heads.""" # At p_heads == 1 both stop on flip 1 (tie), so Alice can never finish strictly earlier. if not (0 < p_heads < 1): raise ValueError("p_heads must be strictly between 0 and 1") # Pair Alice and Bob in simultaneous rounds. Rounds continue only while BOTH flip tails; # conditioning on the first decisive round being (Alice H, Bob T) keeps the round count # geometric with success probability 1 - P(both tails). prob_both_tails = (1 - p_heads) * (1 - p_heads) prob_decisive_round = 1 - prob_both_tails return Fraction(1, 1) / prob_decisive_roundPhase-by-phase collection and first-step renewal
coupon_collector_cost(types, price). Split collection into phasesowned = 0, 1, ..., types - 1. When you already holdowneddistinct designs, each new pack delivers an unseen design with probability(types - owned) / types, requiringtypes / (types - owned)packs on average. On Example 2 (types = 4, price = 6):owned = 0 -> p = 4/4 -> expected packs = 1 owned = 1 -> p = 3/4 -> expected packs = 4/3 owned = 2 -> p = 2/4 -> expected packs = 2 owned = 3 -> p = 1/4 -> expected packs = 4 ------------------------------------------------ Total expected packs = 25/3 => Spend at 6 per pack = 50reroll_expected_payout(sides, threshold). LetEdenote the expected total score. On roll 1 you always earn the average of a single die roll ((sides + 1) / 2), and with probabilitymax(sides - threshold, 0) / sides(face > threshold) you start an identical copy of the game addingEmore:E = mean_single_roll + prob_reroll * E => E = mean_single_roll / (1 - prob_reroll)For Example 2 (
sides = 4, threshold = 2),mean_single_roll = 5/2andprob_reroll = 2/4 = 1/2, giving(5/2) / (1/2) = 5.def coupon_collector_cost(types: int, price: int) -> Fraction: """Problem 7: expected total spent to collect all `types` equally likely toys at `price` per box.""" if types < 0: raise ValueError("types must be non-negative") # Phase `owned`: we have `owned` distinct types, so each new box brings an unseen type # with probability (types - owned) / types, taking types / (types - owned) boxes on average. expected_boxes = Fraction(0) for owned in range(types): expected_boxes_for_next = Fraction(types, types - owned) expected_boxes += expected_boxes_for_next return expected_boxes * price def reroll_expected_payout(sides: int = 6, threshold: int = 3) -> Fraction: """Problem 8: roll, add the result, roll again while the result is > threshold. E[total].""" # If threshold < 1, every face 1..sides exceeds threshold, so the game never terminates. if sides < 1 or threshold < 1: raise ValueError("sides and threshold must be at least 1 so the game can terminate") # By first-step renewal: E = mean_single_roll + P(roll > threshold) * E. mean_single_roll = Fraction(sides + 1, 2) reroll_faces = max(sides - threshold, 0) prob_reroll = Fraction(reroll_faces, sides) return mean_single_roll / (1 - prob_reroll)Bayes' rule and conditional urn updates
disease_given_positive. Trace Example 3 (prevalence = 2%,sensitivity = 95%,false_positive_rate = 4%) on a concrete cohort of10,000people:10,000 people ├── 200 affected (2%) -> 95% test + -> 190 true positives └── 9,800 unaffected (98%) -> 4% test + -> 392 false positives ------------------- 582 total positivesPosterior probability:
190 / 582 = 95/291 ≈ 32.6%.box_posterior(boxes, draws, chosen). Under a uniform prior across containers, posterior weights are proportional to each container's likelihoodC(target_count, draws) / C(total_count, draws). On Example 3 ([(10, 10), (4, 8), (0, 6)],draws = 2,chosen = 0), likelihoods are1,C(4, 2)/C(8, 2) = 6/28 = 3/14, and0, giving1 / (1 + 3/14) = 14/17.second_white_probability(total_balls). Starting withtotal_balls // 2white items, removing1white item leaves(total_balls // 2) - 1white items amongtotal_balls - 1remaining items (4/9whentotal_balls = 10, approaching1/2astotal_ballsgrows huge).def disease_given_positive(prevalence: Fraction, sensitivity: Fraction, false_positive_rate: Fraction) -> Fraction: """Problem 9: P(disease | positive test).""" # Bayes' rule: divide true-positive rate in the population by total positive rate. true_positive_prob = prevalence * sensitivity false_positive_prob = (1 - prevalence) * false_positive_rate return true_positive_prob / (true_positive_prob + false_positive_prob) def box_posterior(boxes: List[Tuple[int, int]], draws: int, chosen: int) -> Fraction: """Problem 16: boxes[i] = (chocolate cookies, total cookies); uniform prior over boxes.""" # likelihoods[i]: P(all `draws` cookies are chocolate | boxes[i] was picked). # Equal priors (1/len(boxes)) cancel between numerator and denominator. likelihoods: List[Fraction] = [] for chocolate_count, total_cookies in boxes: ways_all_chocolate = math.comb(chocolate_count, draws) ways_any_cookies = math.comb(total_cookies, draws) likelihoods.append(Fraction(ways_all_chocolate, ways_any_cookies)) total_likelihood = sum(likelihoods) if total_likelihood == 0: raise ValueError("observed chocolate draw is impossible for every box") return likelihoods[chosen] / total_likelihood def second_white_probability(total_balls: int) -> Fraction: """Problem 17: a bag of total_balls balls, half of them white. P(2nd white | 1st white).""" if total_balls < 2 or total_balls % 2 == 1: raise ValueError("total_balls must be an even integer >= 2") # After drawing 1 white ball without replacement, (white_balls - 1) white balls remain # among (total_balls - 1) remaining balls. white_balls = total_balls // 2 return Fraction(white_balls - 1, total_balls - 1)Dice sample spaces, parity midpoints, and role deduction
strictly_increasing_probability(dice, sides). Everydice-element subset of{1..sides}can be sorted strictly ascending in exactly 1 way, givingC(sides, dice) / sides^dice(C(4, 2) / 16 = 3/8in Example 3).leading_digit_one_probability(dice, sides). Enumerate allsides^diceordered tuples and checkstr(product)[0] == "1". On Example 3 (dice = 2, sides = 4),(1, 1) -> 1,(3, 4) -> 12,(4, 3) -> 12, and(4, 4) -> 16give4/16 = 1/4.average_triple_probability(n). Fora < b < c,b = (a + c) / 2is an integer if and only ifaandcshare the same parity (both even or both odd), and each same-parity pair{a, c}pins down a unique midpointbstrictly between them! In1..10(5evens,5odds),(C(5, 2) + C(5, 2)) / C(10, 3) = 20 / 120 = 1/6.consistent_role_assignmentsandtrue_statement_count. Neither"jester"nor"child"can stand at index0(no preceding speaker exists): - Index0claims"jester":"knight"cannot lie, so index0is"liar"(claim0is false). - Index1claims not"knight":"knight"cannot make that claim truthfully, so claim1is true; after a lying index0,"jester"speaks truthfully, making index1"jester". - Index2claims"knight": after a truthful index1, both remaining candidates ("knight","child") must speak truthfully, forcing index2to be"knight"(claim2is true). - Index3claims not"liar":"child"copies index2's truthfulness and is indeed not"liar"(claim3is true).That leaves
("liar", "jester", "knight", "child")with3true claims.def strictly_increasing_probability(dice: int = 3, sides: int = 6) -> Fraction: """Problem 10: P(the dice, read in order, are strictly increasing).""" # Every subset of `dice` distinct faces has exactly 1 strictly increasing ordering. increasing_rolls = math.comb(sides, dice) total_rolls = sides ** dice return Fraction(increasing_rolls, total_rolls) def leading_digit_one_probability(dice: int = 3, sides: int = 6) -> Fraction: """Problem 11: P(the product of the dice starts with the digit 1).""" # Enumerate all sides^dice equally likely ordered rolls (216 for 3 standard dice). matching_rolls = 0 for roll in itertools.product(range(1, sides + 1), repeat=dice): product = 1 for face_value in roll: product *= face_value if str(product)[0] == "1": matching_rolls += 1 return Fraction(matching_rolls, sides ** dice) def average_triple_probability(n: int = 30) -> Fraction: """Problem 15: three distinct numbers from 1..n; P(one of them is the mean of the other two).""" if n < 3: raise ValueError("need at least 3 numbers") # For a < b < c, b = (a + c) / 2 is an integer iff a and c share the same parity # (both even or both odd), and each such outer pair (a, c) fixes a unique midpoint b. even_count = n // 2 odd_count = n - even_count balanced_triples = math.comb(even_count, 2) + math.comb(odd_count, 2) return Fraction(balanced_triples, math.comb(n, 3)) def statement_is_true(speaker: int, roles: Tuple[str, ...]) -> bool: """Evaluate the literal truth of speaker 0..3's claim under role assignment `roles`.""" role = roles[speaker] if speaker == 0: return role == "jester" # Speaker 1: "I am a jester." if speaker == 1: return role != "knight" # Speaker 2: "I am not a knight." if speaker == 2: return role == "knight" # Speaker 3: "I am the knight." return role != "liar" # Speaker 4: "I am not a liar." def follows_rule(speaker: int, roles: Tuple[str, ...], truths: List[bool]) -> bool: """Check whether `truths[speaker]` obeys the truthfulness rule of `roles[speaker]`.""" role = roles[speaker] if role == "knight": return truths[speaker] if role == "liar": return not truths[speaker] # Both jester and child depend on "the previous speaker", so neither can speak first (index 0). if speaker == 0: return False previous_told_truth = truths[speaker - 1] if role == "jester": return truths[speaker] == (not previous_told_truth) return truths[speaker] == previous_told_truth # child copies previous speaker's truthfulness def consistent_role_assignments() -> List[Tuple[str, ...]]: """Problem 14: all permutations of ROLES consistent with every speaker's rule and statement.""" # Test all 4! = 24 role permutations from speaker 0 to speaker 3. valid_assignments: List[Tuple[str, ...]] = [] for roles in itertools.permutations(ROLES): truths = [statement_is_true(speaker, roles) for speaker in range(4)] if all(follows_rule(speaker, roles, truths) for speaker in range(4)): valid_assignments.append(roles) return valid_assignments def true_statement_count() -> int: """Problem 14: how many of the four statements are true (the assignment must be unique).""" solutions = consistent_role_assignments() if len(solutions) != 1: raise ValueError(f"expected one consistent assignment, found {len(solutions)}") unique_roles = solutions[0] true_count = 0 for speaker in range(4): if statement_is_true(speaker, unique_roles): true_count += 1 return true_countComplete `solution.py`
from typing import Dict, List, Tuple from fractions import Fraction import itertools import math # ROLES: fixed tuple of the four speaker roles in the deduction puzzle ROLES = ("knight", "liar", "jester", "child") # ---------- Counting ---------- def count_arrangements(word: str) -> int: """Problem 1: number of distinct orderings of the letters of word.""" # letter_counts: maps each character -> frequency, e.g. {'L': 2, 'E': 2, 'V': 1} letter_counts: Dict[str, int] = {} for letter in word: letter_counts[letter] = letter_counts.get(letter, 0) + 1 # Start with n! orderings as if identical letters wore distinct labels, # then divide out k! for each letter repeated k times (exact integer division). arrangements = math.factorial(len(word)) for count in letter_counts.values(): arrangements //= math.factorial(count) return arrangements def numbers_from_pairwise_sums(s1: int, s2: int, s3: int) -> List[Fraction]: """Problem 2: the three numbers whose pairwise sums are s1, s2, s3, sorted ascending.""" # Adding (x + y) + (x + z) + (y + z) counts every number twice: 2 * (x + y + z). # Using Fraction handles odd totals cleanly (e.g. sums 1, 1, 1 -> [1/2, 1/2, 1/2]). sum_of_all_three = Fraction(s1 + s2 + s3, 2) # Subtracting each pairwise sum leaves the single number omitted from that pair. first = sum_of_all_three - s1 second = sum_of_all_three - s2 third = sum_of_all_three - s3 return sorted([first, second, third]) def count_rectangles(rows: int, cols: int) -> int: """Problem 12: rectangles (squares included) made of whole cells of a rows x cols board.""" # A grid of `rows` cells high has `rows + 1` horizontal boundary lines (and `cols + 1` vertical). # Any 2 horizontal lines and any 2 vertical lines uniquely frame one axis-aligned rectangle. horizontal_line_pairs = math.comb(rows + 1, 2) vertical_line_pairs = math.comb(cols + 1, 2) return horizontal_line_pairs * vertical_line_pairs # ---------- Drawing without replacement: problems 3, 4 ---------- def distinct_color_probabilities(counts: List[int], draws: int) -> Dict[int, Fraction]: """Problems 3-4: {k: P(exactly k distinct colors)} when drawing without replacement.""" if draws < 0 or any(count < 0 for count in counts): raise ValueError("counts and draws must be non-negative") total_items = sum(counts) total_ways = math.comb(total_items, draws) if total_ways == 0: raise ValueError("cannot draw more items than the bag holds") # per_color_ranges[i]: valid draw counts 0..min(counts[i], draws) from color i per_color_ranges = [range(min(count, draws) + 1) for count in counts] # ways_by_colors: maps distinct_color_count k -> total number of item subsets with k colors ways_by_colors: Dict[int, int] = {} for picks in itertools.product(*per_color_ranges): if sum(picks) != draws: continue # Multiply combinations across colors; since 0 <= picked <= count, ways_for_split >= 1, # which guarantees we only record color counts k that have strictly positive probability. ways_for_split = 1 distinct_colors = 0 for available, picked in zip(counts, picks): ways_for_split *= math.comb(available, picked) if picked > 0: distinct_colors += 1 ways_by_colors[distinct_colors] = ways_by_colors.get(distinct_colors, 0) + ways_for_split probabilities: Dict[int, Fraction] = {} for distinct_colors, ways in ways_by_colors.items(): probabilities[distinct_colors] = Fraction(ways, total_ways) return probabilities # ---------- Expected value of a bet: problem 5 ---------- def exact_order_bet_value(horses: int, places: int, cost: int, payout: int) -> Fraction: """Problem 5: expected profit of paying `cost` to name the first `places` finishers in order.""" # Every ordered list of the top `places` finishers is equally likely: P(horses, places) outcomes. ordered_outcomes = math.perm(horses, places) expected_return = Fraction(payout, ordered_outcomes) return expected_return - cost def horse_option_values() -> Dict[str, Fraction]: """Problem 5: expected profit of each option "a".."e" ("e" = walk away with $10).""" return { "a": exact_order_bet_value(5, 5, 10, 1000), "b": exact_order_bet_value(5, 4, 20, 1000), "c": exact_order_bet_value(5, 3, 30, 1000), "d": exact_order_bet_value(5, 2, 60, 1000), "e": Fraction(10), } # ---------- Coin flips: problems 6, 13 ---------- def even_stop_probability(sides: int = 2) -> Fraction: """Problem 6: flip (or roll a fair `sides`-sided die) until two consecutive results are equal.""" if sides < 1: raise ValueError("need at least one side") # Flip 1 sets the initial value. From flip 2 onward, each flip matches the previous flip # with probability 1/sides. Stopping on n = 2, 4, 6, ... sums to match / (1 - miss^2). prob_match = Fraction(1, sides) prob_miss = 1 - prob_match return prob_match / (1 - prob_miss * prob_miss) def expected_flips_given_fewer(p_heads: Fraction = Fraction(1, 2)) -> Fraction: """Problem 13: E[Alice's flips | Alice needs fewer flips than Bob]; both flip until first heads.""" # At p_heads == 1 both stop on flip 1 (tie), so Alice can never finish strictly earlier. if not (0 < p_heads < 1): raise ValueError("p_heads must be strictly between 0 and 1") # Pair Alice and Bob in simultaneous rounds. Rounds continue only while BOTH flip tails; # conditioning on the first decisive round being (Alice H, Bob T) keeps the round count # geometric with success probability 1 - P(both tails). prob_both_tails = (1 - p_heads) * (1 - p_heads) prob_decisive_round = 1 - prob_both_tails return Fraction(1, 1) / prob_decisive_round # ---------- Expected totals: problems 7, 8 ---------- def coupon_collector_cost(types: int, price: int) -> Fraction: """Problem 7: expected total spent to collect all `types` equally likely toys at `price` per box.""" if types < 0: raise ValueError("types must be non-negative") # Phase `owned`: we have `owned` distinct types, so each new box brings an unseen type # with probability (types - owned) / types, taking types / (types - owned) boxes on average. expected_boxes = Fraction(0) for owned in range(types): expected_boxes_for_next = Fraction(types, types - owned) expected_boxes += expected_boxes_for_next return expected_boxes * price def reroll_expected_payout(sides: int = 6, threshold: int = 3) -> Fraction: """Problem 8: roll, add the result, roll again while the result is > threshold. E[total].""" # If threshold < 1, every face 1..sides exceeds threshold, so the game never terminates. if sides < 1 or threshold < 1: raise ValueError("sides and threshold must be at least 1 so the game can terminate") # By first-step renewal: E = mean_single_roll + P(roll > threshold) * E. mean_single_roll = Fraction(sides + 1, 2) reroll_faces = max(sides - threshold, 0) prob_reroll = Fraction(reroll_faces, sides) return mean_single_roll / (1 - prob_reroll) # ---------- Bayes' rule & conditioning: problems 9, 16, 17 ---------- def disease_given_positive(prevalence: Fraction, sensitivity: Fraction, false_positive_rate: Fraction) -> Fraction: """Problem 9: P(disease | positive test).""" # Bayes' rule: divide true-positive rate in the population by total positive rate. true_positive_prob = prevalence * sensitivity false_positive_prob = (1 - prevalence) * false_positive_rate return true_positive_prob / (true_positive_prob + false_positive_prob) def box_posterior(boxes: List[Tuple[int, int]], draws: int, chosen: int) -> Fraction: """Problem 16: boxes[i] = (chocolate cookies, total cookies); uniform prior over boxes.""" # likelihoods[i]: P(all `draws` cookies are chocolate | boxes[i] was picked). # Equal priors (1/len(boxes)) cancel between numerator and denominator. likelihoods: List[Fraction] = [] for chocolate_count, total_cookies in boxes: ways_all_chocolate = math.comb(chocolate_count, draws) ways_any_cookies = math.comb(total_cookies, draws) likelihoods.append(Fraction(ways_all_chocolate, ways_any_cookies)) total_likelihood = sum(likelihoods) if total_likelihood == 0: raise ValueError("observed chocolate draw is impossible for every box") return likelihoods[chosen] / total_likelihood def second_white_probability(total_balls: int) -> Fraction: """Problem 17: a bag of total_balls balls, half of them white. P(2nd white | 1st white).""" if total_balls < 2 or total_balls % 2 == 1: raise ValueError("total_balls must be an even integer >= 2") # After drawing 1 white ball without replacement, (white_balls - 1) white balls remain # among (total_balls - 1) remaining balls. white_balls = total_balls // 2 return Fraction(white_balls - 1, total_balls - 1) # ---------- Small sample spaces & parity: problems 10, 11, 15 ---------- def strictly_increasing_probability(dice: int = 3, sides: int = 6) -> Fraction: """Problem 10: P(the dice, read in order, are strictly increasing).""" # Every subset of `dice` distinct faces has exactly 1 strictly increasing ordering. increasing_rolls = math.comb(sides, dice) total_rolls = sides ** dice return Fraction(increasing_rolls, total_rolls) def leading_digit_one_probability(dice: int = 3, sides: int = 6) -> Fraction: """Problem 11: P(the product of the dice starts with the digit 1).""" # Enumerate all sides^dice equally likely ordered rolls (216 for 3 standard dice). matching_rolls = 0 for roll in itertools.product(range(1, sides + 1), repeat=dice): product = 1 for face_value in roll: product *= face_value if str(product)[0] == "1": matching_rolls += 1 return Fraction(matching_rolls, sides ** dice) def average_triple_probability(n: int = 30) -> Fraction: """Problem 15: three distinct numbers from 1..n; P(one of them is the mean of the other two).""" if n < 3: raise ValueError("need at least 3 numbers") # For a < b < c, b = (a + c) / 2 is an integer iff a and c share the same parity # (both even or both odd), and each such outer pair (a, c) fixes a unique midpoint b. even_count = n // 2 odd_count = n - even_count balanced_triples = math.comb(even_count, 2) + math.comb(odd_count, 2) return Fraction(balanced_triples, math.comb(n, 3)) # ---------- Logical deduction: problem 14 ---------- def statement_is_true(speaker: int, roles: Tuple[str, ...]) -> bool: """Evaluate the literal truth of speaker 0..3's claim under role assignment `roles`.""" role = roles[speaker] if speaker == 0: return role == "jester" # Speaker 1: "I am a jester." if speaker == 1: return role != "knight" # Speaker 2: "I am not a knight." if speaker == 2: return role == "knight" # Speaker 3: "I am the knight." return role != "liar" # Speaker 4: "I am not a liar." def follows_rule(speaker: int, roles: Tuple[str, ...], truths: List[bool]) -> bool: """Check whether `truths[speaker]` obeys the truthfulness rule of `roles[speaker]`.""" role = roles[speaker] if role == "knight": return truths[speaker] if role == "liar": return not truths[speaker] # Both jester and child depend on "the previous speaker", so neither can speak first (index 0). if speaker == 0: return False previous_told_truth = truths[speaker - 1] if role == "jester": return truths[speaker] == (not previous_told_truth) return truths[speaker] == previous_told_truth # child copies previous speaker's truthfulness def consistent_role_assignments() -> List[Tuple[str, ...]]: """Problem 14: all permutations of ROLES consistent with every speaker's rule and statement.""" # Test all 4! = 24 role permutations from speaker 0 to speaker 3. valid_assignments: List[Tuple[str, ...]] = [] for roles in itertools.permutations(ROLES): truths = [statement_is_true(speaker, roles) for speaker in range(4)] if all(follows_rule(speaker, roles, truths) for speaker in range(4)): valid_assignments.append(roles) return valid_assignments def true_statement_count() -> int: """Problem 14: how many of the four statements are true (the assignment must be unique).""" solutions = consistent_role_assignments() if len(solutions) != 1: raise ValueError(f"expected one consistent assignment, found {len(solutions)}") unique_roles = solutions[0] true_count = 0 for speaker in range(4): if statement_is_true(speaker, unique_roles): true_count += 1 return true_count✅ Submit now — all tests should pass.
Intuition & how it works
Think of a probability and combinatorics toolkit like a carpenter's workbench: even when 18 functions look unrelated on the surface, nearly every one comes apart cleanly with four foundational ideas:
- Count the defining choices rather than every object — instead of scanning rectangles cell by cell or sorting dice rolls one by one, count the decisions that uniquely pin one down (two horizontal and two vertical grid lines, or a subset of
dicedistinct faces). - Use first-step or stage-by-stage resets — when a random process can repeat indefinitely, examine what happens on one step; memorylessness (the property that future independent rolls or tosses do not depend on how the process arrived at the present state) turns an infinite sum into a one-line linear equation like
E = 2.5 + 0.5 * E. - Count a concrete cohort for conditional probability — Bayes' rule (revising the probability of an underlying cause after observing new evidence) becomes transparent when you split a hypothetical crowd of
10,000people into true positives and false positives. - Represent rational values exactly (
Fraction) — keeping exact numerator/denominator fractions prevents floating-point rounding drift and allows direct equality checks against brute-force enumeration.
Why do ad-hoc shortcuts fail? Listing permutations manually, truncating infinite series by hand, or trusting gut intuition on rare-condition screening breaks down immediately. Gut intuition overlooks base rates (how rare a condition is prior to testing) and forgets that conditioning on "Player 1 beats Player 2" filters out long runs of tails.
Watch two examples from our statement in miniature:
- Grid rectangles (3 × 4 grid in Example 1): Rather than tallying 1×1, 1×2, ..., 3×4 sizes separately (and risking a missed shape), observe that a 3 × 4 grid is bounded by 4 horizontal lines and 5 vertical lines. Picking 2 horizontal lines (C(4, 2) = 6) and 2 vertical lines (C(5, 2) = 10) immediately produces 6 * 10 = 60 rectangles.
- Screening test (2% prevalence, 95% sensitivity, 4% false-positive rate in Example 3): Out of 10,000 people, 200 have the condition (190 test +) and 9,800 do not (392 falsely test +). Out of 190 + 392 = 582 positive results, 190 / 582 = 95/291 ≈ 32.6% truly have the condition.
Complexity
- Closed-form functions (
numbers_from_pairwise_sums,count_rectangles,exact_order_bet_value,horse_option_values,even_stop_probability,expected_flips_given_fewer,reroll_expected_payout,disease_given_positive,second_white_probability,strictly_increasing_probability,average_triple_probability) — O(1) time and O(1) space: Each evaluates a constant number of binomial, permutation, power, orFractionoperations (up to big-integer arithmetic for huge inputs). count_arrangements(word)— O(n) time and O(k) space: Scans thencharacters ofwordonce to countkdistinct symbols, then computesn!and divides by each symbol's factorial frequency.coupon_collector_costandbox_posterior— O(types) and O(len(boxes)) time, O(1) / O(len(boxes)) space:coupon_collector_costsumstypesstage expectations using linearity of expectation (the rule that the expected sum of random waits equals the sum of their individual expectations), andbox_posteriorevaluates one combinatorial likelihood per container.distinct_color_probabilities— O(∏(min(count_i, draws) + 1) × m) time and O(m) space: Iterates over bounded draw tuples acrossmcategories (3 × 3 × 2 = 18tuples on[2, 3, 1]withdraws = 2) and multipliesmbinomial coefficients per valid split.leading_digit_one_probability— O(sides^dice × dice) time and O(dice) space: Visits allsides^diceordered outcomes (16for(2, 4),216for(3, 6)) and multiplies thedicefaces.consistent_role_assignments/true_statement_count— O(r! × r) time and O(r) space: Tests all4! = 24permutations of ther = 4speaker roles across4rule checks each (96checks total).
Edge cases
- Position
0in speaker role deduction: Both"jester"and"child"reference the immediately preceding speaker, which does not exist at index0. Disallowing both at index0yields the unique valid assignment("liar", "jester", "knight", "child")with3true claims. - Fractional or negative unknowns in
numbers_from_pairwise_sums: Odd totals like(1, 1, 1)sum to3, producing[1/2, 1/2, 1/2]cleanly viaFraction(s1 + s2 + s3, 2); negative sums work identically. - Non-terminating rerolls and impossible strict wins:
reroll_expected_payoutraisesValueErrorwhenthreshold < 1(since every face1..sideswould trigger infinite rerolls), andexpected_flips_given_fewerraisesValueErrorwhenp_heads == 1(both players tie on toss 1, makingA < Bhave probability0). - Finite vs huge urns in
second_white_probability: Without replacement,(N/2 - 1) / (N - 1)equals4/9 ≈ 0.444atN = 10, approaching1/2asymptotically only asNgrows large.
Common mistakes
- Repeated characters in
count_arrangements: Dividing5!on"LEVEL"by only one2!instead of2! * 2!, overcounting by2×(60instead of30). - Dividing pairwise sums by
3instead of2: In(x + y) + (x + z) + (y + z) = 56, each variable appears twice, sox + y + z = 28, not56 / 3. - Choosing cell rows instead of grid lines in
count_rectangles: ComputingC(rows, 2) * C(cols, 2)(3 * 6 = 18on3 × 4) instead ofC(rows + 1, 2) * C(cols + 1, 2) = 60drops every 1-row or 1-column rectangle. - Treating without-replacement draws as independent: Using
(2/6)^2 + (3/6)^2 + (1/6)^2 = 7/18(sampling with replacement) instead of(1 + 3 + 0) / 15 = 4/15on[2, 3, 1]. - Guessing
1/2foreven_stop_probability(2): Roll 1 can never terminate the game, whereas roll 2 (an even count!) already halts with probability1/sides, biasing even counts upward (2/3for a coin,3/5for a 3-sided die). - Ignoring conditioning in
expected_flips_given_fewer: Returning the unconditional mean1 / p_heads(3forp_heads = 1/3) instead of1 / (1 - (1 - p_heads)^2) = 9/5, forgetting that winning the race rules out long streaks of tails. - Confusing sensitivity with posterior probability: Reporting
95%in Example 3 by mistakingP(+ | condition)forP(condition | +) = 95/291 ≈ 32.6%.
Alternative approaches
- Dynamic programming for larger dice or urn inputs: When
diceorlen(counts)grows large (say50dice or100categories), replace explicit Cartesian enumeration with dynamic programming (maintaining a table of exact counts over reachable states one die or one category at a time). - Benford's law intuition for
leading_digit_one_probability: Benford's law (the observation that products of many independent random variables begin with base-10 digitdwith probability nearlog10(1 + 1/d)) giveslog10(2) ≈ 0.3010for digit1, remarkably close to65/216 ≈ 0.3009on three 6-sided dice!
Follow-up questions
- In disease_given_positive, if an individual receives two independent positive test results in a row, how do you update the posterior probability cleanly? Work in odds (
P(condition) : P(no condition)). On Example 3 (2%prior,95%sensitivity,4%false-positive rate), prior odds start at2 : 98 = 1 : 49, and each independent positive result multiplies the affected side by the likelihood ratio0.95 / 0.04 = 95/4. One positive result raises odds to95 : 196(95/291 ≈ 32.6%), and a second independent positive result multiplies by95/4again to9025 : 784, jumping the posterior probability to9025 / 9809 ≈ 92.0%! - In coupon_collector_cost, how wide is the spread (standard deviation) around the expected spend? Each phase
k = 0..types - 1is an independent geometric random variable (count of packs until a new design of probabilityp_k = (types - k) / types, with variance(1 - p_k) / p_k^2), so variances add directly across phases. On Example 2 (types = 4, price = 6), pack variances are0 + 4/9 + 2 + 12 = 130/9 ≈ 14.44, giving a standard deviation ofsqrt(130) / 3 ≈ 3.80packs — or6 * 3.80 ≈ 22.80around the expected spend of50, with over83%of total variance coming from hunting the final design! - In even_stop_probability, what is the expected total number of rolls before two consecutive outcomes match? Roll 1 always sets the initial face, and from roll 2 onward each roll independently matches the previous face with probability
1 / sides. That makesN - 1a geometric random variable with meansides, soE[N] = 1 + sides(3tosses on average for a fair coin,4rolls for a 3-sided die, and7rolls for a 6-sided die).
Follow-up questions
- In disease_given_positive, if an individual receives two independent positive test results in a row, how do you update the posterior probability cleanly?
- In coupon_collector_cost, how wide is the spread (standard deviation) around the expected spend?
- In even_stop_probability, what is the expected total number of rolls before two consecutive outcomes match?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes