Created
November 1, 2024 13:37
-
-
Save vndee/0ade211397f389c6b797c1f6a0742a35 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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