|
12 | 12 | # 4. After the first toss, you'll need another loop to keep flipping while you
|
13 | 13 | # get the same result as the first flip.
|
14 | 14 |
|
15 |
| -fromrandomimportrandint |
| 15 | +importrandom |
16 | 16 |
|
17 | 17 |
|
18 | 18 | defsingle_trial():
|
19 |
| -toss=randint(0,1) |
20 |
| -total_flips=1 |
| 19 | +"""Simulate repeatedly a coing until both heads and tails are seen.""" |
| 20 | +# This function uses random.randint() to simulate a single coin toss. |
| 21 | +# randing(0, 1) randomly returns 0 or 1 with equal probability. We can |
| 22 | +# use 0 to represent heads and 1 to represent tails. |
21 | 23 |
|
22 |
| -whiletoss==randint(0,1): |
23 |
| -total_flips+=1 |
24 |
| -toss=randint(0,1) |
| 24 | +# Flip the coin the first time |
| 25 | +flip_result=random.randint(0,1) |
| 26 | +# Keep a tally of how many times the coin has been flipped. We've only |
| 27 | +# flipped once so the initial count is 1. |
| 28 | +flip_count=1 |
25 | 29 |
|
26 |
| -total_flips+=1 |
27 |
| -returntotal_flips |
| 30 | +# Continue to flip the coin until randint(0, 1) returns something |
| 31 | +# different than the original flip_result |
| 32 | +whileflip_result==random.randint(0,1): |
| 33 | +flip_count=flip_count+1 |
| 34 | + |
| 35 | +# The last step in the loop flipped the coin but didn't update the tally, |
| 36 | +# so we need to increase the flip_count by 1 |
| 37 | +flip_count=flip_count+1 |
| 38 | +returnflip_count |
28 | 39 |
|
29 | 40 |
|
30 | 41 | defflip_trial_avg(num_trials):
|
| 42 | +"""Calculate the average number of flips per trial over num_trials total trials.""" |
31 | 43 | total=0
|
32 | 44 | fortrialinrange(num_trials):
|
33 |
| -total+=single_trial() |
| 45 | +total=total+single_trial() |
34 | 46 | returntotal/num_trials
|
35 | 47 |
|
36 | 48 |
|
37 |
| -print(f"The average number of coin flips was{flip_trial_avg(10000)}") |
| 49 | +print(f"The average number of coin flips was{flip_trial_avg(10_000)}") |