Probability calculator
Simulating randomness usually means import random - but that makes a lesson
impossible to grade with an exact ==, since the "right" answer changes
every run. The fix: a linear congruential generator (LCG) , a tiny formula
that produces a deterministic stream of numbers that look random but are
100% reproducible from a fixed seed. Same seed in, same numbers out, every
single time.
You're given the generator already written - it's not something you need to
implement:
def lcg ( seed ) :
state = seed
while True :
state = ( state * 1103515245 + 12345 ) % ( 2 * * 31 )
yield state / ( 2 * * 31 )
lcg(seed) is a generator (phase 7): calling next() on it gives you the
next float in [0, 1). To use one of those floats to pick an item from
bag (a list of color-name strings, with duplicates - e.g. ['red']*5 + ['blue']*3 for a bag weighted 5-to-3 toward red), scale it into a valid
index: bag[int(r * len(bag))].
Your task: write simulate_draws(bag, n, seed). Create one generator
with lcg(seed), then draw from bag with replacement n times - each
draw pulls the next float from the generator and uses it to pick one item
from bag as described above. Return a dict mapping each color that was
drawn to how many times it came up.
You'll practice:
Driving a generator with next() to get a reproducible sequence of values
Turning a [0, 1) float into a valid list index
Building up a count dict across n iterations
Show a hint
Show solution
Related reading: Probability: Measuring Uncertainty →
Previous Next