Skip to content

Instantly share code, notes, and snippets.

@vndee
Created November 1, 2024 13:37
Show Gist options
  • Save vndee/0ade211397f389c6b797c1f6a0742a35 to your computer and use it in GitHub Desktop.
Save vndee/0ade211397f389c6b797c1f6a0742a35 to your computer and use it in GitHub Desktop.
def random_choice(rng, options, weights=None):
"""Pick something randomly from a list"""
if weights is None:
# Simple case: everything has equal chance
index = rng.extract_number() % len(options)
return options[index]
# Complex case: some things are more likely than others
# Generate random value in [0, sum(weights))
r = random_float(rng) * sum(weights)
# Find which bucket r falls into
cumsum = 0
for option, weight in zip(options, weights):
cumsum += weight
if r < cumsum:
return option
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment