Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f5b7c7b

Browse files
committed
Improve recipe by showing results of intermediate steps
1 parent 8c9d99f commit f5b7c7b

1 file changed

Lines changed: 6 additions & 0 deletions

File tree

Doc/library/random.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,9 @@ population with repeats::
328328

329329
>>> weighted_choices = [('Red', 3), ('Blue', 2), ('Yellow', 1), ('Green', 4)]
330330
>>> population = [val for val, cnt in weighted_choices for i in range(cnt)]
331+
>>> population
332+
['Red', 'Red', 'Red', 'Blue', 'Blue', 'Yellow', 'Green', 'Green', 'Green', 'Green']
333+
331334
>>> random.choice(population)
332335
'Green'
333336

@@ -337,6 +340,9 @@ with :func:`itertools.accumulate`, and then locate the random value with
337340

338341
>>> choices, weights = zip(*weighted_choices)
339342
>>> cumdist = list(itertools.accumulate(weights))
343+
>>> cumdist # [3, 3+2, 3+2+1, 3+2+1+4]
344+
[3, 5, 6, 10]
345+
340346
>>> x = random.random() * cumdist[-1]
341347
>>> choices[bisect.bisect(cumdist, x)]
342348
'Blue'

0 commit comments

Comments
 (0)