choosing random numbers with weights/probability?

Evan Simpson evan at
Mon Jun 21 21:15:51 CEST 1999

In this simple case, you could use:

weighted = [0, 1, 2, 2]
item = list[whrandom.choice(weighted)]

If you really need arbitrary weights, try:

list = [('one', 0.25), ('two', 0.25), ('three', 0.5)]
def weighted_choice(list):
  from whrandom import uniform
  n = uniform(0, 1)
  for item, weight in list:
    if n < weight:
    n = n - weight
  return item

kevinsl wrote in message <929987267.6227 at>...
I've been using the whrandom.choice routine and it's very
useful. But is there any way to add weights or
probabilities of being chosen to the items in the list?



Is there any way to say that 'one' and 'two' have a 25%
chance of being chosen, and 'three' has a 50% chance?

More information about the Python-list mailing list