Can someone help me explaining the solution for below Realpython assignment task? Solution i found seems confusing.
Write a python script that uses coin toss simulations to determine the answer to this slightly more complex probability puzzle: I keep flipping a fair coin until I've seen it land on both heads and tails at least once each - in other words, after I flip the coin the first time, I continue to flip it until I get a different result. On average, how many times will I have to flip the coin total? Again, the actual probability could be worked out, but the point here is to simulate the event using randint. To get the expected average number of tosses, you should set a variable trials is 10000 and a variable flips is 0 , then add 1 to your flips variable every time a coin toss is made. Then you can print flips / trials at the end of the code to see what the average number of flips was.
from random import randint
flips = 0
trials = 10000
for i in range(trials):
first_flip = randint(0, 1)
while randint(0, 1) == first_flip:
flips += 1 # Every flip after the first flip.
print("flips done is {}".format(flips))
print(flips / trials + 2.0) # Initial trial and final trial added.
In the above case if the first_flip is 0 and the while loop condition produces 1 at the very first random attempt, the for loop iterates without adding the flips. Also, if the while loop runs when random attempts equals first_flip, within the while loop trail ie, value for "i" in the for loop is not added. In short the final number of flips is more or less than the number of trials.
Can someone help me explaining the logic behind this or a better python script?