]> granicus.if.org Git - python/commitdiff
Improve recipe by showing results of intermediate steps
authorRaymond Hettinger <python@rcn.com>
Mon, 5 Sep 2016 20:15:02 +0000 (13:15 -0700)
committerRaymond Hettinger <python@rcn.com>
Mon, 5 Sep 2016 20:15:02 +0000 (13:15 -0700)
Doc/library/random.rst

index 677090a5ff75cb0a48a310c5492c421f6c5467ae..22f18a0cd5bd2e8421ef4846acaa07811cfcf84a 100644 (file)
@@ -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'