Random selection

Roger Miller roger.miller at nova-sol.com
Fri May 18 17:57:27 EDT 2007


On May 17, 10:39 pm, Tartifola <tartif... at gmail.com> wrote:
> Hi,
> 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?
> Thanks

This of course depends on your definition of "best".  There is a fast
and simple technique if all probabilities are multiples of 1/n for a
reasonably small n, or if you are willing to round them to such.
Suppose for example that the probabilities are [0.42, 0.23, 0.35].
Create a list of 100 items with 42 0's, 23 1's, and 35 2's, then
select a random element using random.choice() or
equivalent.




More information about the Python-list mailing list