Commit d64c898b authored by Raymond Hettinger's avatar Raymond Hettinger

Improve recipe by showing results of intermediate steps

parent 51a1fa13
...@@ -328,6 +328,9 @@ population with repeats:: ...@@ -328,6 +328,9 @@ population with repeats::
>>> weighted_choices = [('Red', 3), ('Blue', 2), ('Yellow', 1), ('Green', 4)] >>> weighted_choices = [('Red', 3), ('Blue', 2), ('Yellow', 1), ('Green', 4)]
>>> population = [val for val, cnt in weighted_choices for i in range(cnt)] >>> 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) >>> random.choice(population)
'Green' 'Green'
...@@ -337,6 +340,9 @@ with :func:`itertools.accumulate`, and then locate the random value with ...@@ -337,6 +340,9 @@ with :func:`itertools.accumulate`, and then locate the random value with
>>> choices, weights = zip(*weighted_choices) >>> choices, weights = zip(*weighted_choices)
>>> cumdist = list(itertools.accumulate(weights)) >>> 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] >>> x = random.random() * cumdist[-1]
>>> choices[bisect.bisect(cumdist, x)] >>> choices[bisect.bisect(cumdist, x)]
'Blue' 'Blue'
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment