summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2016-09-05 20:15:02 (GMT)
committerRaymond Hettinger <python@rcn.com>2016-09-05 20:15:02 (GMT)
commitf5b7c7bfc1876ac0f262f2f05952ec8841542f0a (patch)
treed6b562df3d89d6a1fdadddb90d981ba6fb3f23a4
parent8c9d99ff2227d7a069b29f26004f33d65a1df177 (diff)
downloadcpython-f5b7c7bfc1876ac0f262f2f05952ec8841542f0a.zip
cpython-f5b7c7bfc1876ac0f262f2f05952ec8841542f0a.tar.gz
cpython-f5b7c7bfc1876ac0f262f2f05952ec8841542f0a.tar.bz2
Improve recipe by showing results of intermediate steps
-rw-r--r--Doc/library/random.rst6
1 files changed, 6 insertions, 0 deletions
diff --git a/Doc/library/random.rst b/Doc/library/random.rst
index 677090a..22f18a0 100644
--- a/Doc/library/random.rst
+++ b/Doc/library/random.rst
@@ -328,6 +328,9 @@ 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)]
+ >>> population
+ ['Red', 'Red', 'Red', 'Blue', 'Blue', 'Yellow', 'Green', 'Green', 'Green', 'Green']
+
>>> random.choice(population)
'Green'
@@ -337,6 +340,9 @@ with :func:`itertools.accumulate`, and then locate the random value with
>>> choices, weights = zip(*weighted_choices)
>>> cumdist = list(itertools.accumulate(weights))
+ >>> cumdist # [3, 3+2, 3+2+1, 3+2+1+4]
+ [3, 5, 6, 10]
+
>>> x = random.random() * cumdist[-1]
>>> choices[bisect.bisect(cumdist, x)]
'Blue'