Smarter way of doing this?
Roberto Antonio Ferreira De Almeida
roberto at dealmeida.net
Tue Feb 3 08:01:09 EST 2004
Max M wrote:
> Roberto A. F. De Almeida wrote:
>
>> 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]
>
> uh, that's hard to read :-)
Yes, I know. I just wanted to see if I could do it in one line. :)
But it just calculates the cumulative probability, and gets the first
one which passes a random value between 0 and the sum of the probabilities.
> But doesn't random.random()*sum(p) get executed for each probability in p?
I actually don't know. You could call random.random() out of the list
comprehension... :)
R.
More information about the Python-list
mailing list