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

Skip to content

Commit 6befb64

Browse files
committed
Extend and improve the examples for the random module
1 parent ac0720e commit 6befb64

1 file changed

Lines changed: 29 additions & 5 deletions

File tree

Doc/library/random.rst

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -345,8 +345,8 @@ Basic examples::
345345
>>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive
346346
26
347347

348-
>>> choice('abcdefghij') # Single random element from a sequence
349-
'c'
348+
>>> choice(['win', 'lose', 'draw']) # Single random element from a sequence
349+
'draw'
350350

351351
>>> deck = 'ace two three four'.split()
352352
>>> shuffle(deck) # Shuffle a list
@@ -370,8 +370,9 @@ Simulations::
370370
>>> print(seen.count('tens') / 20)
371371
0.15
372372

373-
# Estimate the probability of getting 5 or more heads from 7 spins
374-
# of a biased coin that settles on heads 60% of the time.
373+
# Estimate the probability of getting 5 or more heads
374+
# from 7 spins of a biased coin that settles on heads
375+
# 60% of the time.
375376
>>> n = 10000
376377
>>> cw = [0.60, 1.00]
377378
>>> sum(choices('HT', cum_weights=cw, k=7).count('H') >= 5 for i in range(n)) / n
@@ -416,4 +417,27 @@ between the effects of a drug versus a placebo::
416417
print(f'{n} label reshufflings produced only {count} instances with a difference')
417418
print(f'at least as extreme as the observed difference of {observed_diff:.1f}.')
418419
print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null')
419-
print(f'hypothesis that the observed difference occurred due to chance.')
420+
print(f'hypothesis that there is no difference between the drug and the placebo.')
421+
422+
Simulation of arrival times and service deliveries in a single server queue::
423+
424+
from random import gauss, expovariate
425+
426+
average_arrival_interval = 5.6
427+
average_service_time = 5.0
428+
stdev_service_time = 0.5
429+
430+
num_waiting = 0
431+
arrival = service_end = 0.0
432+
for i in range(10000):
433+
num_waiting += 1
434+
arrival += expovariate(1.0 / average_arrival_interval)
435+
print(f'{arrival:6.1f} arrived')
436+
437+
while arrival > service_end:
438+
num_waiting -= 1
439+
service_start = service_end if num_waiting else arrival
440+
service_time = gauss(average_service_time, stdev_service_time)
441+
service_end = service_start + service_time
442+
print(f'\t\t{service_start:.1f} to {service_end:.1f} serviced')
443+

0 commit comments

Comments
 (0)