Welcome, guest | Sign In | My Account | Store | Cart

weighted choice from list

Python, 14 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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

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.

1 comment

mozbugbox 17 years, 9 months ago  # | flag

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 &lt; weight:
            break
        n = n - weight
    return item
Created by kevin parks on Fri, 15 Mar 2002 (PSF)
Python recipes (4591)
kevin parks's recipes (2)

Required Modules

Other Information and Tasks