Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #53851
| Date | 2013-09-09 10:49 +1000 |
|---|---|
| From | Cameron Simpson <cs@zip.com.au> |
| Subject | Re: Weighted choices |
| References | <kl4q29ta0kn2tnfoju13dg8nni4vjvco80@4ax.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.161.1378687769.5461.python-list@python.org> (permalink) |
On 08Sep2013 20:21, Dennis Lee Bieber <wlfraed@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@zip.com.au>
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Weighted choices Cameron Simpson <cs@zip.com.au> - 2013-09-09 10:49 +1000
csiph-web