summaryrefslogtreecommitdiffstats
path: root/Doc/library/random.rst
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2010-12-02 02:41:33 (GMT)
committerRaymond Hettinger <python@rcn.com>2010-12-02 02:41:33 (GMT)
commit2fdc7b1f759e557c57d16e91b9ac53f2b441c0be (patch)
tree598d4c5faea652c59d62596f849383fcc7580fc0 /Doc/library/random.rst
parentc74d518e73c1e209abc5dd1d39371dff3d3e8f36 (diff)
downloadcpython-2fdc7b1f759e557c57d16e91b9ac53f2b441c0be.zip
cpython-2fdc7b1f759e557c57d16e91b9ac53f2b441c0be.tar.gz
cpython-2fdc7b1f759e557c57d16e91b9ac53f2b441c0be.tar.bz2
Add an example to the random docs.
Diffstat (limited to 'Doc/library/random.rst')
-rw-r--r--Doc/library/random.rst26
1 files changed, 26 insertions, 0 deletions
diff --git a/Doc/library/random.rst b/Doc/library/random.rst
index 7aa0894..10c2f3c 100644
--- a/Doc/library/random.rst
+++ b/Doc/library/random.rst
@@ -295,3 +295,29 @@ change across Python versions, but two aspects are guaranteed not to change:
* The generator's :meth:`random` method will continue to produce the same
sequence when the compatible seeder is given the same seed.
+
+
+.. _random-examples:
+
+Examples and Recipes
+====================
+
+A common task is to make a :func:`random.choice` with weighted probababilites.
+
+If the weights are small integer ratios, a simple technique is to build a sample
+population with repeats::
+
+ >>> weighted_choices = [('Red', 3), ('Blue', 2), ('Yellow', 1), ('Green', 4)]
+ >>> population = [val for val, cnt in weighted_choices for i in range(cnt)]
+ >>> random.choice(population)
+ 'Green'
+
+A more general approach is to arrange the weights in a cumulative probability
+distribution with :func:`itertools.accumulate`, and then locate the random value
+with :func:`bisect.bisect`::
+
+ >>> choices, weights = zip(*weighted_choices)
+ >>> cumdist = list(itertools.accumulate(weights))
+ >>> x = random.random() * cumdist[-1]
+ >>> choices[bisect.bisect(cumdist, x)]
+ 'Blue'