9/17
Part 4 of 7 · Waiting timesLearn and do

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