Probability you can compute: Bayes' rule, expected values and waiting times

55 min7 partsFoundationFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Turn a base rate and a test's two error rates into the chance you actually want, with natural frequencies
  • Use Bayes' rule in odds form, and chain several pieces of evidence
  • Find expected values with linearity and indicator variables, even when events depend on each other
  • Work out the expected number of loops in code that retries at random
  • Build a fair random number from another one with rejection sampling, and count its cost

Bayes' rule and waiting times, the way the rounds ask

Netflix data science candidates report a Bayes' rule calculation in the statistics round (2 reports), and an OpenAI coding round asked for the expected number of iterations of a function that loops at random (1 source). This lesson's practice problem puts both in code, in three levels:

  1. posterior(prior, sensitivity, false_positive_rate): the chance an order is fraud once a check flags it. Then update(prior, results), which applies several independent results in order, positive or negative.
  2. expected_tries(p), expected_tries_for(successes, p) and coupon_collector(n): how long you wait for a success, for several, and for every one of n kinds.
  3. make_rand7(rand5): a fair 1 to 7 from a fair 1 to 5.
CallReturns
posterior(0.01, 0.95, 0.05)0.161: even after a flag, the order is more likely good
expected_tries(0.25)4.0
coupon_collector(10)29.3
make_rand7(rand5)(), many times1 to 7, each a seventh of the time

The lesson works on one shop throughout: a fraud check, a label printer, coupon codes and patch designs. It goes from conditional probability to Bayes' rule in odds form, then expected values, waiting times and rejection sampling. Eight steps end with a small task in the editor.

Part 1 of 7about 8 min
Conditional probability

A positive result means less than it seems when the condition is rare

Netflix data science candidates report a Bayes' rule calculation in the statistics round (2 reports). The trap in every version is the same: a test that's usually right, applied to something rare.

The outdoor shop runs a fraud check on its orders. 1 order in 200 is fraud. The check flags 90% of the fraud, and it also flags 2% of the good orders by mistake.

Predict

The check flags an order. What's the chance it's fraud?

Count orders, not probabilities

Gigerenzer and Hoffrage showed that Bayesian reasoning is computationally simpler in frequency formats than with probabilities. So picture 10,000 orders and count:

orders = 10_000
# 1 order in 200 is fraud
fraud = orders * 0.005
good = orders - fraud
# the check flags 90% of fraud
flagged_fraud = fraud * 0.90
# and 2% of good orders
flagged_good = good * 0.02
print(f"{flagged_fraud:.0f} fraud and {flagged_good:.0f} good orders flagged")
print(f"P(fraud | flagged) = {flagged_fraud / (flagged_fraud + flagged_good):.1%}")
Predict

Out of 10,000 orders, how many does the check flag in all?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

A woman's mammogram is positive. About how likely is it that she has cancer?

Pick an answer above to see the rest
Part 1 done
Part 2 of 7about 16 min
Bayes' rule

Bayes' rule turns the rates you know into the one you want

The Stanford Encyclopedia of Philosophy calls Bayes' theorem a simple formula for calculating conditional probabilities:

P(F∣flag)=P(flag∣F) P(F)P(flag)P(F \mid \text{flag}) = \frac{P(\text{flag} \mid F)\, P(F)}{P(\text{flag})}

Here F is fraud. The top is the flagged fraud. The bottom, P(flag), is everything flagged: the flagged fraud plus the flagged good orders. They're the same two counts as the tree, divided by 10,000.

In odds form, each piece of evidence multiplies

Odds are the chance of yes over the chance of no. Bayes' rule in odds form is one multiplication: the odds after the evidence are the odds before it times the likelihood ratio, how many times more often the evidence shows up when the answer is yes.

Predict

The check flags 90% of fraud and 2% of good orders. What's the likelihood ratio of a flag?

Pick an answer above to see the rest
Predict

After the flag and the reviewer's confirmation, about how likely is fraud?

Pick one to see what it prints.
Pick an answer above to see the rest

Accuracy alone tells you nothing

MIT's text points out a simple way to make a test that's 99% accurate: always say negative.

Predict

A vendor sells a fraud check that's 99.5% accurate on the shop's orders. What should you ask?

Pick an answer above to see the rest

A negative result is evidence too

A check that comes back clean lowers the odds. Its likelihood ratio uses the misses: how often the evidence is absent when the answer is yes, over how often it's absent when the answer is no, (1 − sensitivity) / (1 − false positive rate).

ResultLikelihood ratioFor the reviewer: 80% of fraud, 5% of good orders
positivesensitivity / false positive rate0.80 / 0.05 = 16
negative(1 − sensitivity) / (1 − false positive rate)0.20 / 0.95 = 0.21

A flagged order that the reviewer then clears goes from 18.4% to about 4.5%. Each result's answer is the next one's prior, so results chain in order.

In the editor, write update(prior, results), which chains results that are positive or negative. It prints a flagged order that the reviewer confirms, then one the reviewer clears.

Part 2 done
Part 3 of 7about 7 min
Expected value

An expected value is a weighted average, and averages add

An expected value is the average a random quantity takes over many repeats: each value times its probability, added up. Its most useful property is linearity: MIT's text says the expected value of a sum is the sum of the expected values. Grinstead and Snell add that this holds whether or not the parts are independent, which they call the First Fundamental Mystery of Probability.

The trick that makes linearity powerful is the indicator: a variable that's 1 when an event happens and 0 otherwise. Its expected value is just the event's probability. To count how many things happen on average, add the indicators' probabilities.

The shop's label printer jams, and the 20 shipping labels for a batch of 20 parcels go on in a random order.

import random

rng = random.Random(1)
parcels, trials = 20, 100_000
matches = 0
for _ in range(trials):
    labels = list(range(parcels))
    # the labels land on the parcels in a random order
    rng.shuffle(labels)
    matches += sum(parcel == label for parcel, label in enumerate(labels))
print(f"{matches / trials:.3f} parcels a batch get their own label, on average")
Predict

On average, how many of the 20 parcels still get their own label?

Pick one to see what it prints.
Predict

With 1,000 parcels in a batch instead of 20, what's the average?

Pick an answer above to see the rest
Part 3 done
Part 4 of 7about 6 min
Waiting times

Waiting for a success takes 1/p tries on average

An OpenAI coding round asked for the expected number of iterations of a function that loops at random (1 source). Most such loops repeat a try until it succeeds, and MIT's text gives the rule: if a step fails independently with probability p, the expected number of steps up to the first failure is 1/p. Swap failure for success and it's the same rule.

The shop makes coupon codes by drawing a random code and drawing again if that code is already taken. Python's random() returns a float in the range 0.0 <= X < 1.0, so rng.random() < used is true with chance used.

import random


def draws_until_unused(rng, used):
    """Draws random coupon codes until one isn't taken yet."""
    draws = 1
    # this code is taken, so draw again
    while rng.random() < used:
        draws += 1
    return draws


rng = random.Random(2)
for used in (0.5, 0.6, 0.9):
    average = sum(draws_until_unused(rng, used) for _ in range(100_000)) / 100_000
    print(f"{used:.0%} of codes taken: {average:.2f} draws on average")
Predict

60% of the codes are taken. How many draws does a new code take on average?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 4 done
Part 5 of 7about 8 min
Rejection sampling

Build a fair 1 to 7 from a 1 to 5 by throwing some draws away

LeetCode's problem 470 asks for a uniform random number from 1 to 10 given one from 1 to 7, and follows up with the expected number of calls. Here's the same question one size down: a fair 1 to 7 from rand5, a fair 1 to 5.

Predict

Is (rand5() + rand5()) % 7 + 1 a fair 1 to 7?

Pick an answer above to see the rest
Predict

How many calls to rand5 does one rand7 take on average?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 5 done
Part 6 of 7about 3 min
The worked example

A Bayes' rule question, as a stats round asks it

Here are two questions as interviewers ask them, worked out loud.

10% of users are horror fans. A horror fan watches a horror trailer to the end 60% of the time, and everyone else 20% of the time. A user watched to the end. How likely are they a horror fan?

1. Write down the three numbers: the base rate, 10%, and the two rates, 60% and 20%.

2. Count 1,000 users. 100 fans, of whom 60 finish. 900 others, of whom 180 finish.

3. Check it in odds. Prior odds of 1 to 9, times a likelihood ratio of 60 / 20 = 3, gives 3 to 9, which is 1 to 3.

Predict

So how likely is the user to be a horror fan?

Pick an answer above to see the rest

An expected iterations question, as a coding round asks it

The second one comes from a coding round.

This function draws random points in the unit square until one lands inside the quarter circle. How many iterations does it run on average?

The method: find the chance one pass ends the loop, check that every pass has the same chance independently, and take one over it. Here a pass ends the loop when the point lands in the quarter circle, an area of π/4.

import math
import random

rng = random.Random(4)


def iterations():
    """Draws points in the unit square until one lands inside the quarter circle."""
    count = 1
    while rng.random() ** 2 + rng.random() ** 2 > 1:
        count += 1
    return count


average = sum(iterations() for _ in range(100_000)) / 100_000
print(f"{average:.3f} iterations on average")
Predict

What's the expected number of iterations?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 6 done
Part 7 of 7about 7 min
Follow-ups

Collecting every kind

Three follow-ups come up after these questions. The first is a classic.

The shop puts one of 6 patch designs in every order. How many orders until a customer has all 6? A simulation:

import random

rng = random.Random(5)
designs, trials = 6, 100_000
total = 0
for _ in range(trials):
    seen = set()
    while len(seen) < designs:
        # each order brings one design at random
        seen.add(rng.randrange(designs))
        total += 1
print(f"{total / trials:.1f} orders on average to collect all {designs} designs")
Predict

About how many orders does it take to collect all 6 designs?

Pick one to see what it prints.
Pick an answer above to see the rest

At least one

The chance that at least one of several independent events happens is easiest through its opposite: 1 minus the chance that none happens.

Predict

1 order in 200 is fraud. In a batch of 20 orders, what's the chance at least one is fraud?

Evidence that isn't independent

Two checks that look at the same signal aren't independent given the truth. Multiplying their likelihood ratios counts that signal twice and makes the posterior too confident. Ask how the second check works before you chain it.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
5 questions
  1. 1.1 order in 200 is fraud, a check flags 90% of fraud and 2% of good orders. What share of flagged orders is fraud?

  2. 2.What does Bayes' rule look like in odds form?

  3. 3.20 labels go on 20 parcels in a random order. What's the expected number of parcels with their own label?

  4. 4.A loop repeats with chance 0.75 after each pass. How many passes does it make on average?

  5. 5.Why does a fair 1 to 7 from two calls of rand5 throw away 4 of the 25 pairs?

Practice

Sources (19)
  1. Bayes' Theorem · James Joyce, Stanford Encyclopedia of Philosophy · Sep 30, 2003
    “Bayes' Theorem is a simple mathematical formula used for calculating conditional probabilities.”
  2. How to Improve Bayesian Reasoning Without Instruction: Frequency Formats · Gigerenzer and Hoffrage, Psychological Review 102(4) · Oct 1, 1995
    “The authors show that Bayesian algorithms are computationally simpler in frequency formats than in the probability formats used in previous research.”
  3. How to Improve Bayesian Reasoning Without Instruction: Frequency Formats · Gigerenzer and Hoffrage, Psychological Review 102(4) · Oct 1, 1995
    “10 out of every 1,000 women ... have breast cancer. 8 of every 10 women with breast cancer will get a positive mammography. 95 out of every 990 women without breast cancer will also get a positive mammography.”
  4. How to Improve Bayesian Reasoning Without Instruction: Frequency Formats · Gigerenzer and Hoffrage, Psychological Review 102(4) · Oct 1, 1995
    “Eddy (1982) reported that 95 out of 100 physicians estimated the posterior probability p(cancer|positive) to be between 70% and 80%, rather than 7.8%.”
  5. Helping Doctors and Patients Make Sense of Health Statistics · Gigerenzer, Gaissmaier, Kurz-Milcke, Schwartz and Woloshin, Psychological Science in the Public Interest 8(2) · Nov 1, 2007
    “The probability that a woman has breast cancer is 1% (prevalence) ... the probability that she tests positive is 90% (sensitivity) ... the probability that she nevertheless tests positive is 9% (false-positive rate)”
  6. Helping Doctors and Patients Make Sense of Health Statistics · Gigerenzer, Gaissmaier, Kurz-Milcke, Schwartz and Woloshin, Psychological Science in the Public Interest 8(2) · Nov 1, 2007
    “The number of physicians who found the best answer, as documented in medical studies, was slightly less than chance (21%).”
  7. Helping Doctors and Patients Make Sense of Health Statistics · Gigerenzer, Gaissmaier, Kurz-Milcke, Schwartz and Woloshin, Psychological Science in the Public Interest 8(2) · Nov 1, 2007
    “After learning during the training session how to translate conditional probabilities into natural frequencies ... 87% of them now understood that 1 in 10 is the best answer”
  8. Mathematics for Computer Science, 17.4.4 Natural Frequencies · Lehman, Leighton and Meyer, MIT OpenCourseWare · May 18, 2015
    “The number of healthy individuals is so large that even the mere 5% with false positive results overwhelm the number of genuinely positive results from the truly ill.”
  9. Introduction to Probability, Chapter 4: Conditional Probability (Example 4.17) · Grinstead and Snell, Dartmouth CHANCE Project · Jul 4, 2006
    “When a group of second-year medical students was asked this question, over half of the students incorrectly guessed the probability to be greater than .5.”
  10. Mathematics for Computer Science, 17.4.3 Four Steps Again · Lehman, Leighton and Meyer, MIT OpenCourseWare · May 18, 2015
    “there is a simple way to make a test that is 99% accurate: always return a negative result!”
  11. Mathematics for Computer Science, 18.5 Linearity of Expectation · Lehman, Leighton and Meyer, MIT OpenCourseWare · May 18, 2015
    “Its simplest form says that the expected value of a sum of random variables is the sum of the expected values of the variables.”
  12. Introduction to Probability, 6.1 Expected Value · Grinstead and Snell, Dartmouth CHANCE Project · Jul 4, 2006
    “The fact that expectations add, whether or not the summands are mutually independent, is sometimes referred to as the First Fundamental Mystery of Probability.”
  13. Mathematics for Computer Science, 18.4.3 The Expected Value of an Indicator Random Variable · Lehman, Leighton and Meyer, MIT OpenCourseWare · May 18, 2015
    “The expected value of an indicator random variable for an event is just the probability of that event.”
  14. Mathematics for Computer Science, 18.4.6 Mean Time to Failure · Lehman, Leighton and Meyer, MIT OpenCourseWare · May 18, 2015
    “If a system independently fails at each time step with probability p, then the expected number of steps up to the first failure is 1/p.”
  15. random: Generate pseudo-random numbers · Python Software Foundation, Python 3 documentation · Nov 19, 2026
    “Return the next random floating-point number in the range 0.0 <= X < 1.0”
  16. random: Generate pseudo-random numbers · Python Software Foundation, Python 3 documentation · Nov 19, 2026
    “The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets module.”
  17. 470. Implement Rand10() Using Rand7() · LeetCode · Nov 19, 2026
    “Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10].”
  18. 470. Implement Rand10() Using Rand7() · LeetCode · Nov 19, 2026
    “What is the expected value for the number of calls to rand7() function?”
  19. Mathematics for Computer Science, 18.5.4 The Coupon Collector Problem · Lehman, Leighton and Meyer, MIT OpenCourseWare · May 18, 2015
    “Thus, the expected number of meals until we get a new kind of car is n/(n - k) by the Mean Time to Failure rule.”