Skip to content

Instantly share code, notes, and snippets.

@joshuaskelly
Last active August 20, 2017 17:08
Show Gist options
  • Save joshuaskelly/c14d50a3d0b8fb69e073c1d84ae14783 to your computer and use it in GitHub Desktop.
Save joshuaskelly/c14d50a3d0b8fb69e073c1d84ae14783 to your computer and use it in GitHub Desktop.
Randomly select a value from a weighted list.
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