-1

I have a list of integers and I would like to be able to choose a random number based on the weights in a that list.

For example let's say I have a list like this: List = [20,40,80,60].

The chances of me choosing the number 1 (or 0 depending on how you see it) would be 10% and the chance of getting the number 3 would be 30%.

How would I go about doing this in a pythonic way?

doniyor
  • 36,596
  • 57
  • 175
  • 260
TumbaBit
  • 117
  • 2
  • 12

1 Answers1

1

A simple algorithm might look like this:

import bisect
import random
def random_choice(choices, weights):
    """
    >>> a = ['Hit', 'Out']
    >>> b = [.3, .7]
    >>> random_choice(a,b)
    """
    cumsums = []
    c = 0
    for weight in weights:
        c += weight
        cumsums.append(c)
    rnd = random.uniform(0, c)
    i = bisect.bisect(cumsums, rnd)
    return choices[i]

Demo:

>>> random_choice(list('ABCD'), weights=[20,40,80,60])
'C'

However, there are algorithms which are more efficient if you plan on calling random_choice many times. See for example, the Alias method and this article for a comparison of many options.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677