Skip to content

Instantly share code, notes, and snippets.

@pauladam
Created February 14, 2010 22:03
Show Gist options
  • Save pauladam/304295 to your computer and use it in GitHub Desktop.
Save pauladam/304295 to your computer and use it in GitHub Desktop.
Random choice with weighted probabilities
# typical to sum over your list of items perhaps
# performing some calculation on each item
normalizing_constant = \
sum([calc(item) for item in items if filter(item)])
r = random.random()
for item in items:
prob = get_probability(item) / normalizing_constant
if prob > r:
# keep this guy
break
r -= prob
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment