Smarter way of doing this?
Mel Wilson
mwilson at the-wire.com
Mon Feb 2 13:02:12 EST 2004
In article <401e4d57$0$295$edfadb0f at dread12.news.tele.dk>,
Max M <maxm at mxm.dk> wrote:
>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?
My usual way is:
import random
def choose_by_probability (values, probabilities):
cumul = 0.0
for prob, item in zip (probabilities, values):
cumul += prob
if prob > random.random()*cumul:
selected = item
return selected
def run_tests (n):
D = {}
for i in xrange (n):
j = choose_by_probability (['item 1', 'item 2', 'item 3']
, [0.66, 0.33, 0.17])
D[j] = D.get (j, 0) + 1
s = D.items()
s.sort()
for k, v in s:
print k, float(v)/n
print "Total:", sum([v for k, v in D.items()])
run_tests (10000)
Regards. Mel.
More information about the Python-list
mailing list