Skip to content

Instantly share code, notes, and snippets.

@redrush85
Last active December 31, 2016 11:33
Show Gist options
  • Save redrush85/2dc16a3b2dc70a4ff6e5cf1827c556ad to your computer and use it in GitHub Desktop.
Save redrush85/2dc16a3b2dc70a4ff6e5cf1827c556ad to your computer and use it in GitHub Desktop.
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