ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: windex.py
Submitter: kevin parks (other recipes)
Last Updated: 2002/03/15
Version no: 1.0
Category:

 

4 stars 2 vote(s)


Description:

weighted choice from list

Source: Text Source

import random

def windex(lst):
	'''an attempt to make a random.choose() function that makes weighted choices
	
	accepts a list of tuples with the item and probability as a pair
	like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)]
	>>> y=windex(x)'''
	n = random.uniform(0, 1)
	for item, weight in lst:
		if n < weight:
			break
		n = n - weight
	return item

Discussion:

This makes weighted random choices just as the doc string says. We batted this around on the tutor list a while and folks there imporved it, but whatever flaws remain are mine.



Add comment

Number of comments: 1

Not specified Not specified, 2006/06/18
Generalize to arbitery weight. Weights are not need to add up to 1.0

import random

def windex(lst):
	'''an attempt to make a random.choose() function that makes weighted choices
	
	accepts a list of tuples with the item and probability as a pair'''

        wtotal = sum([x[1] for x in lst])
	n = random.uniform(0, wtotal)
	for item, weight in lst:
		if n < weight:
			break
		n = n - weight
	return item


Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Treat the Win32 Registry ...

4. Watching a directory ...

5. Union Find data structure

6. Function Decorators by ...

7. MS SQL Server log monitor

8. Table objects with ...

9. wx twisted support using ...

10. More accurate sum




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.