faqts : Computers : Programming : Languages : Python : Snippets : Maths

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 5 people (60%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

Choosing random numbers with weights/probability?

Jul 5th, 2000 10:02
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 241, Michael Hudson


"""
Packages: maths.random
"""
"""
> I've been using the whrandom.choice routine and it's very
> useful. But is there any way to add weights or
> probabilities of being chosen to the items in the list?
> 
> example:
> 
> list=['one','two','three']
> item=whrandom.choice(list)
> 
> Is there any way to say that 'one' and 'two' have a 25%
> chance of being chosen, and 'three' has a 50% chance?
One very obvious, not very extensible, way:
"""
import whrandom, random # added by PSST
list=['one','two','three','three']
item=whrandom.choice(list)
"""
(NB: list is a builtin; using list as a variable name can lead to
confusion)
A not very efficient but more general method:
"""
def weighted_choice(choices):
    tot = 0
    for w,v in choices:
        tot = tot + w
    d = random.random()*tot
    tot = 0
    for w,v in choices:
        tot = tot + w
        if tot > d:
            return v
list=[(0.25,'one'),(0.25,'two'),(0.5,'three')]
print weighted_choice(list)
"""
seems to work. Haven't tested it much, so please don't rely on it...
HTH
Michael
"""