Last active
December 31, 2016 11:33
-
-
Save redrush85/2dc16a3b2dc70a4ff6e5cf1827c556ad to your computer and use it in GitHub Desktop.
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 weighted_choice(lst, attr_name): | |
total = sum(getattr(item, attr_name, 1) for item in lst) | |
r = random.uniform(0, total) | |
upto = 0 | |
for index, item in enumerate(lst): | |
if upto + getattr(item, attr_name, 1) >= r: | |
return index, item | |
upto += getattr(item, attr_name, 1) | |
return None, None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment