Weighted choices

Cameron Simpson cs at zip.com.au
Sun Sep 8 20:49:13 EDT 2013


On 08Sep2013 20:21, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:
| 	However, I would not use a dictionary for this. An ordered list should
| work better... for small samples a list containing repeats (by weight) of
| each choice, and then use a random integer whose range is 0..len(list)-1
| would suffice.
| 
| choices = ["apple", "apple", "apple", ..., "kiwi", "kiwi" ]

Scales badly as soon as the weights get even slightly big (or high res).

| 	For longer lists, storing a tuple with the accumulating weight, and
| scanning from the beginning
| 
| choices = [(10, "Apple"), (10+20, "Pear"), (10+20+15, "Banana")... ]
| 
| generate random integer in the range of the sum of the weights, and accept
| the last tuple whose first element is less than the integer.

Search it with the bisect module, not linearly!

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>



More information about the Python-list mailing list