Created
October 31, 2014 01:22
-
-
Save mengzhuo/85e6baa18ef02bf1a324 to your computer and use it in GitHub Desktop.
Roulette_wheel_select base on Python
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
def roulette_wheel_select(groups): | |
""" | |
Groups should format in list: | |
(weigth (positive), content) | |
More weight more chance that we pick this content | |
BUT not every time | |
i.e. | |
[(1, '1'), | |
(2, '2')] | |
""" | |
total_p = reduce(lambda s, x: s+x, | |
[x[0] for x in groups]) | |
assert total_p > 0, "Total percent %d <= 0" % total_p | |
seed = random.uniform(0, total_p) | |
upto = 0 | |
for weight, content in groups: | |
upto += weight | |
if upto >= seed: | |
return content |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how about it?