[issue40541] Add optional weights parameter to random.sample()

Raymond Hettinger report at bugs.python.org
Wed May 6 18:35:20 EDT 2020


New submission from Raymond Hettinger <raymond.hettinger at gmail.com>:

I've seen multiple requests for this and it isn't obvious how to do it with the existing tooling.  

The example currently given in the recipes section isn't scalable because it involves expanding the population into a big list with repeated elements:

      sample(['x', 'x', 'x', 'x', 'y', 'y', 'z'], k=5)

Example task:  Given an urn with 8 red balls, 2 white balls, and 3 green balls, choose ten without replacement:

    >>> population = ['red', 'blue', 'green']
    >>> weights =    [  8,      5,      3   ]
    >>> sample(population, weights=weights, k=10)
    ['red', 'green', 'blue', 'red', 'green', 'blue', 'red', 'blue', 'red', 'blue']

I could also add *cum_weights* as an optional optimization but think it best to wait until someone asks for it ;-)

----------
components: Library (Lib)
messages: 368307
nosy: rhettinger, tim.peters
priority: normal
severity: normal
status: open
title: Add optional weights parameter to random.sample()
type: enhancement
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40541>
_______________________________________


More information about the Python-bugs-list mailing list