Code

Side Quest: A Thousand Expeditions

One random expedition tells you very little. A thousand of them tell you the odds. Running something many times with random numbers is called a simulation. (It's also called the Monte Carlo method, after a famous casino.)

Printing every step of 1,000 expeditions would flood the screen. Good simulations stay quiet while they run, then print a short summary at the end.

Bounded random walks

Each expedition is a random walk: Pip steps forward or back at random. A walk could wander for ages, so give it a step limit. Then every walk is sure to end.

def walk(rng, max_steps):
    pos = 0
    for _ in range(max_steps):
        pos += rng.choice([-1, 1])
        if pos == 3:
            return "treasure"   # stop early
    return "tired"              # out of steps

One generator for the whole survey

Make one random.Random(seed) and pass it to every expedition. If each expedition made its own Random(seed) with the same seed, they would all walk exactly the same path!

Assignment

  1. expedition(rng, max_steps): start at 0. Take up to max_steps steps, each one rng.choice([-1, 1]). Return "treasure" as soon as the position reaches 3, "cliff" as soon as it reaches -3, or "tired" if the steps run out.
  2. survey(seed, trips, max_steps): make one random.Random(seed), run trips expeditions with it and return a dict counting each outcome. Always include all three keys, e.g. {"treasure": 41, "cliff": 39, "tired": 20}.
  3. Neither function prints anything.