On 08Sep2013 20:21, Dennis Lee Bieber <wlfr...@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 <c...@zip.com.au> -- https://mail.python.org/mailman/listinfo/python-list