Smarter way of doing this?
Roberto A. F. De Almeida
roberto at dealmeida.net
Tue Feb 3 12:26:29 CET 2004
Max M <maxm at mxm.dk> wrote in message news:<401e4d57$0$295$edfadb0f at dread12.news.tele.dk>...
> 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?
In one line:
v = ['item 1','item 2','item 3',]
p = [0.66, 0.33, 0.16]
[v[i] for i,j in enumerate(p) if sum(p[:i]) > (random.random()*sum(p))][0]
R.
More information about the Python-list
mailing list