Created
February 14, 2010 22:03
-
-
Save pauladam/304295 to your computer and use it in GitHub Desktop.
Random choice with weighted probabilities
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
# 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