Created
September 2, 2013 02:53
-
-
Save madisonmay/6408842 to your computer and use it in GitHub Desktop.
Random weighted choice generator function
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
import itertools, bisect | |
def weighted_choice(seq, weights): | |
cumulative_dist = itertools.accumulate(weights) | |
while True: | |
x = random.random() * cumdist[-1] | |
i = [bisect.bisect(cumulative_dist, x)] | |
yield seq[i] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment