Skip to content

Commit 97bc285

Browse files
committed
Remove extra coin flip and clean up challenge solution
1 parent 0881715 commit 97bc285

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

ch08-conditional-logic/8c-challenge-simulate-a-coin-toss-experiment.py

+22-10
Original file line numberDiff line numberDiff line change
@@ -12,26 +12,38 @@
1212
# 4. After the first toss, you'll need another loop to keep flipping while you
1313
# get the same result as the first flip.
1414

15-
from random import randint
15+
import random
1616

1717

1818
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.
2123

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
2529

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
2839

2940

3041
def flip_trial_avg(num_trials):
42+
"""Calculate the average number of flips per trial over num_trials total trials."""
3143
total = 0
3244
for trial in range(num_trials):
33-
total += single_trial()
45+
total = total + single_trial()
3446
return total / num_trials
3547

3648

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

Comments
 (0)