|
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 |
| -from random import randint |
| 15 | +import random |
16 | 16 |
|
17 | 17 |
|
18 | 18 | def single_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 |
| - while toss == 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 |
| - return total_flips |
| 30 | + # Continue to flip the coin until randint(0, 1) returns something |
| 31 | + # different than the original flip_result |
| 32 | + while flip_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 | + return flip_count |
28 | 39 |
|
29 | 40 |
|
30 | 41 | def flip_trial_avg(num_trials):
|
| 42 | + """Calculate the average number of flips per trial over num_trials total trials.""" |
31 | 43 | total = 0
|
32 | 44 | for trial in range(num_trials):
|
33 |
| - total += single_trial() |
| 45 | + total = total + single_trial() |
34 | 46 | return total / 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)}") |
0 commit comments