Let's do one more probability experiment before we move on. A few pages ago, we talked about flipping a coin and how likely it would be to get a bunch of heads in a row. Why don't we try an experiment to see how often we get 10 heads in a row? It won't happen very often, so we're going to have to do a lot of coin flips before we see it. Why don't we try
1,000,000! With a real coin, that would take . . . a long time.
If you could do one coin toss every 5 seconds, that would be 12 per minute, or 720 per hour. If you could do coin tosses for 12 hours a day (after all, you still have to eat and sleep), you could do about 8,500 tosses a day. So it would take about 115 days (about 4 months) to do one million coin tosses. But with a computer, we can do it in seconds. (Okay, maybe a few minutes, because we have to write the program first.)
For this program, in addition to flipping the coin, we have to keep track of when we get 10 heads in a row. One way to do this is to use a counter. A counter is a variable used to count something.
We'll need two counters. One will be for the number of heads we have tossed in a row. Let's call it heads_in_row. The other is for the number of times we get 10 heads in a row. Let's call it ten_heads_in_row. This is what the program will do:
■ Whenever we get heads, the heads_in_row counter will increase by 1.
■ Whenever we get tails, the heads_in_row counter will go back to 0.
■ When the heads_in_row counter reaches 10, we'll increase the ten_heads_in_row counter by 1 and set the heads_in_row counter back to 0, to start over.
■ At the end, we'll print a message saying how many times we got 10 heads in a row.
Listing 23.3 Looking for 10 heads in a row from random import * coin = ["Heads", "Tails"] heads_in_row = 0 ten_heads_in_row = 0 for i in range (1000000):
if heads_in_row == 10: Got 10 heads in a row, ten_heads_in_row += ----- increments counter heads_in_row = 0
print "We got 10 heads in a row", ten_heads_in_row, "times."
When I ran this program, it said TT
r 3 We got 10 heads in a row 510 times.
I ran the program a few times, and the number was always around 500. That means, in a million coin tosses, we should expect to get 10 heads in a row about 500 times, or about once every 2,000 tosses (1,000,000 / 500 = 2,000).
Was this article helpful?
Playing bowling with your friends can help you decide if it is indeed the hobby that you want to invest your time on today. Aside from that, it can help you get a better feel of the sport. More importantly, when you play with your friends, it would become a more fun activity, which you can look forward to each week.