DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Weighted Random Choice

09.17.2005
| 10918 views |
  • submit to reddit
        From Kevin Parks's <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117241>recipe</a>
import random

def w_choice(lst):
	n = random.uniform(0, 1)
	for item, weight in lst:
		if n < weight:
			break
		n = n - weight
	return item
Usage, similar to random.choice but must specify probabilities.
>>> x = w_choice( [('one',0.25), ('two',0.25), ('three',0.5)] )