Skip to content

Instantly share code, notes, and snippets.

@mengzhuo
Created October 31, 2014 01:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mengzhuo/85e6baa18ef02bf1a324 to your computer and use it in GitHub Desktop.
Save mengzhuo/85e6baa18ef02bf1a324 to your computer and use it in GitHub Desktop.
Roulette_wheel_select base on Python
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
@yidinghan
Copy link

total_p = sum(map(lambda x: x[0], groups))

how about it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment