Last active
August 20, 2017 17:08
-
-
Save joshuaskelly/c14d50a3d0b8fb69e073c1d84ae14783 to your computer and use it in GitHub Desktop.
Randomly select a value from a weighted list.
This file contains hidden or 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
import random | |
from bisect import bisect | |
from itertools import accumulate | |
# The weighted list is represented as a sequence of weight-value pairs. | |
items = [(3, "apple"), (3, "banana"), (2, "cherry"), (1, "durian")] | |
# Build a list of weighted indexes. | |
weighted_indexes = list(accumulate([i[0] for i in items])) | |
# Choose one of these at random for the list index. | |
chosen = items[bisect(weighted_indexes, random.random() * weighted_indexes[-1])][1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment