Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit97bc285

Browse files
committed
Remove extra coin flip and clean up challenge solution
1 parent0881715 commit97bc285

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

Lines changed: 22 additions & 10 deletions
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-
fromrandomimportrandint
15+
importrandom
1616

1717

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

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
2529

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
2839

2940

3041
defflip_trial_avg(num_trials):
42+
"""Calculate the average number of flips per trial over num_trials total trials."""
3143
total=0
3244
fortrialinrange(num_trials):
33-
total+=single_trial()
45+
total=total+single_trial()
3446
returntotal/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)

[8]ページ先頭

©2009-2025 Movatter.jp