diff options
author | Raymond Hettinger <python@rcn.com> | 2016-09-07 00:15:29 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2016-09-07 00:15:29 (GMT) |
commit | e8f1e002c642e30b820181cd87ae9d187d709f59 (patch) | |
tree | f5cb3c6514eec58c8bf2071dbaa7b71473f5d2d4 /Doc | |
parent | 63d98bcd4c88eea1c4b50dae95da662284813114 (diff) | |
download | cpython-e8f1e002c642e30b820181cd87ae9d187d709f59.zip cpython-e8f1e002c642e30b820181cd87ae9d187d709f59.tar.gz cpython-e8f1e002c642e30b820181cd87ae9d187d709f59.tar.bz2 |
Issue #18844: Add random.weighted_choices()
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/library/random.rst | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/Doc/library/random.rst b/Doc/library/random.rst index 6dc54d2..330cce1 100644 --- a/Doc/library/random.rst +++ b/Doc/library/random.rst @@ -124,6 +124,27 @@ Functions for sequences: Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises :exc:`IndexError`. +.. function:: weighted_choices(k, population, weights=None, *, cum_weights=None) + + Return a *k* sized list of elements chosen from the *population* with replacement. + If the *population* is empty, raises :exc:`IndexError`. + + If a *weights* sequence is specified, selections are made according to the + relative weights. Alternatively, if a *cum_weights* sequence is given, the + selections are made according to the cumulative weights. For example, the + relative weights ``[10, 5, 30, 5]`` are equivalent to the cumulative + weights ``[10, 15, 45, 50]``. Internally, the relative weights are + converted to cumulative weights before making selections, so supplying the + cumulative weights saves work. + + If neither *weights* nor *cum_weights* are specified, selections are made + with equal probability. If a weights sequence is supplied, it must be + the same length as the *population* sequence. It is a :exc:`TypeError` + to specify both *weights* and *cum_weights*. + + The *weights* or *cum_weights* can use any numeric type that interoperates + with the :class:`float` values returned by :func:`random` (that includes + integers, floats, and fractions but excludes decimals). .. function:: shuffle(x[, random]) |