Random selection

Peter Otten __peter__ at web.de
Fri May 18 05:05:21 EDT 2007


Tartifola wrote:

> I have a list with probabilities as elements
> 
> [p1,p2,p3]
> 
> with of course p1+p2+p3=1. I'd like to draw a
> random element from this list, based on the probabilities contained in
> the list itself, and return its index.
> 
> Any help on the best way to do that?

import random
import bisect

def draw(probabilities):
    sigma = 0.0
    ps = []
    for p in probabilities:
        sigma += p
        ps.append(sigma)

    _bisect = bisect.bisect
    _random = random.random
    while 1:
        yield _bisect(ps, _random())

if __name__ == "__main__":
    from itertools import islice
    histo = [0]*4
    for i in islice(draw([0.2, 0.3, 0.5]), 100000):
        histo[i] += 1
    print histo





More information about the Python-list mailing list