Skip to content

Commit 71c62e1

Browse files
committed
Neaten-up and extend the examples in the random module docs.
1 parent 2238131 commit 71c62e1

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

Doc/library/random.rst

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -364,25 +364,29 @@ Basic examples::
364364

365365
Simulations::
366366

367-
# Six roulette wheel spins (weighted sampling with replacement)
367+
>>> # Six roulette wheel spins (weighted sampling with replacement)
368368
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
369369
['red', 'green', 'black', 'black', 'red', 'black']
370370

371-
# Deal 20 cards without replacement from a deck of 52 playing cards
372-
# and determine the proportion of cards with a ten-value (i.e. a ten,
373-
# jack, queen, or king).
371+
>>> # Deal 20 cards without replacement from a deck of 52 playing cards
372+
>>> # and determine the proportion of cards with a ten-value
373+
>>> # (a ten, jack, queen, or king).
374374
>>> deck = collections.Counter(tens=16, low_cards=36)
375375
>>> seen = sample(list(deck.elements()), k=20)
376-
>>> print(seen.count('tens') / 20)
376+
>>> seen.count('tens') / 20
377377
0.15
378378

379-
# Estimate the probability of getting 5 or more heads from 7 spins
380-
# of a biased coin that settles on heads 60% of the time.
381-
>>> n = 10000
382-
>>> cw = [0.60, 1.00]
383-
>>> sum(choices('HT', cum_weights=cw, k=7).count('H') >= 5 for i in range(n)) / n
379+
>>> # Estimate the probability of getting 5 or more heads from 7 spins
380+
>>> # of a biased coin that settles on heads 60% of the time.
381+
>>> trial = lambda: choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
382+
>>> sum(trial() for i in range(10000)) / 10000
384383
0.4169
385384

385+
>>> # Probability of the median of 5 samples being in middle two quartiles
386+
>>> trial = lambda : 2500 <= sorted(choices(range(10000), k=5))[2] < 7500
387+
>>> sum(trial() for i in range(10000)) / 10000
388+
0.7958
389+
386390
Example of `statistical bootstrapping
387391
<https://en.wikipedia.org/wiki/Bootstrapping_(statistics)>`_ using resampling
388392
with replacement to estimate a confidence interval for the mean of a sample of

0 commit comments

Comments
 (0)