diff --git a/ch08-conditional-logic/8c-challenge-simulate-a-coin-toss-experiment.py b/ch08-conditional-logic/8c-challenge-simulate-a-coin-toss-experiment.py index 5d1e075..e42167c 100644 --- a/ch08-conditional-logic/8c-challenge-simulate-a-coin-toss-experiment.py +++ b/ch08-conditional-logic/8c-challenge-simulate-a-coin-toss-experiment.py @@ -12,38 +12,29 @@ # 4. After the first toss, you'll need another loop to keep flipping while you # get the same result as the first flip. -import random - - -def single_trial(): - """Simulate repeatedly a coing until both heads and tails are seen.""" - # This function uses random.randint() to simulate a single coin toss. - # randing(0, 1) randomly returns 0 or 1 with equal probability. We can - # use 0 to represent heads and 1 to represent tails. - - # Flip the coin the first time - flip_result = random.randint(0, 1) - # Keep a tally of how many times the coin has been flipped. We've only - # flipped once so the initial count is 1. - flip_count = 1 - - # Continue to flip the coin until randint(0, 1) returns something - # different than the original flip_result - while flip_result == random.randint(0, 1): - flip_count = flip_count + 1 - - # The last step in the loop flipped the coin but didn't update the tally, - # so we need to increase the flip_count by 1 - flip_count = flip_count + 1 - return flip_count +# Here is a simpler-to-read thus more pythonistic version, I think :P +import random -def flip_trial_avg(num_trials): - """Calculate the average number of flips per trial over num_trials total trials.""" - total = 0 - for trial in range(num_trials): - total = total + single_trial() - return total / num_trials +def coin_flip_trial(): + heads = 0 + tails = 0 + tries = 0 +# As long as heads OR tails are zero, we have not had one of each. + while heads == 0 or tails == 0: + result = random.randint(0,1) + tries = tries + 1 + if result == 1: + heads = heads + 1 + else: + tails = tails + 1 + return tries + +# So let's now do that 10,000 times and then report the average number of trials it took. +tries_needed = 0 +for x in range(10_000): + tries_needed = tries_needed + coin_flip_trial() + +print(f"It takes on average {tries_needed / 10_000:.2f} tries to get both a heads and a tails.") -print(f"The average number of coin flips was {flip_trial_avg(10_000)}")
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: