Smarter way of doing this?

Max M maxm at mxm.dk
Mon Feb 2 08:15:14 EST 2004


I have written this function, "choose_by_probability()"

It takes a list of probabilities in the range 0.00-1.00, and it must 
then randomly select one of the probabilities and return it's index.

The idea is to have two lists, one with a value, and another with a 
probability. The value then gets randomly selected from its probability.

values = ['item 1','item 2','item 3',]
probabilities = [0.66, 0.33, 0.16]

print values[choose_by_probability(probabilities)]
 >>'item 1'

etc...

I just wondered if anybody has a better way of doing it, as this seems 
nastily squared to me?


regards Max M


###################

from random import random

def choose_by_probability(probabilities):
     "Randomly selects an index from a list of probabilities"
     rnd = random() * sum(probabilities)
     range_start = 0.0
     for i in range(len(probabilities)):
         probability = probabilities[i]
         range_end = range_start + probability
         if range_start < rnd < range_end:
             return i
         range_start = range_end


probabilities = []
for f in range(0,16):
     probabilities.append(1.0 / (f+1.0))

print probabilities

# writing it out sorted to do a visual test...
result = []
for i in range(100):
     result.append(choose_by_probability(probabilities))
result.sort()
print result



More information about the Python-list mailing list