
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
expedition(rng, max_steps): start at0. Take up tomax_stepssteps, each onerng.choice([-1, 1]). Return"treasure"as soon as the position reaches3,"cliff"as soon as it reaches-3, or"tired"if the steps run out.survey(seed, trips, max_steps): make onerandom.Random(seed), runtripsexpeditions with it and return a dict counting each outcome. Always include all three keys, e.g.{"treasure": 41, "cliff": 39, "tired": 20}.- Neither function prints anything.
expedition(rng, max_steps): start at0. Take up tomax_stepssteps, each onerng.choice([-1, 1]). Return"treasure"as soon as the position reaches3,"cliff"as soon as it reaches-3, or"tired"if the steps run out.survey(seed, trips, max_steps): make onerandom.Random(seed), runtripsexpeditions with it and return a dict counting each outcome. Always include all three keys, e.g.{"treasure": 41, "cliff": 39, "tired": 20}.- Neither function prints anything.
main.py Python sleeping
Press Run to try your code, then Check to test it.