I assigned my students in comp sci to write a code that simulates flipping a coin 100 times, storing the results in a list. Look for a streak of 6 heads ( or more ), or 6 tails ( or more ). If you find a streak, then consider the trial a success. Repeat this experiment 10,000 times. Use this to determine the probability of finding a streak of 6 heads or 6 tails.
Theoretically this probability should be ~80%.
EDIT: It is possible I misinterpreted this theoretical probability. I found this probability here: https://math.stackexchange.com/questions/2736117/what-is-the-probability-of-getting-6-or-more-heads-or-tails-in-a-row-after-flipp
My code is giving me a probability of about 54%, the probability of getting exactly 6 in a row. However, if I got 7, 8, 9, or more in a row, my code should mark this as a success, correct?
I understand my code checks for steaks of 6, but if there is a streak of 7, 8, 9, ... it would still mark it as a success. There must be something I'm missing here...
Attached is my code:
import random
numberofstreaks = 0
for experimentnumber in range(10000):
result = []
for i in range(100):
flip = random.randint(0,1)
result.append(flip)
for i in range(len(result)-6):
if result[i:i+6] == ([0,0,0,0,0,0] or [1,1,1,1,1,1]):
numberofstreaks += 1
break
print(numberofstreaks)
print('Chance of steak:',(numberofstreaks/100))
Note: They are currently learning about lists, which is why their code must contain the use of lists.
Thanks ahead of time!
A slight correction:
import random
numberofstreaks = 0
for experimentnumber in range(10000):
result = []
for i in range(100):
flip = random.randint(0,1)
result.append(flip)
for i in range(len(result)-6):
if result[i:i+6] == [0,0,0,0,0,0] or result[i: i+6] == [1,1,1,1,1,1]:
numberofstreaks += 1
break
print(numberofstreaks)
print('Chance of steak:',(numberofstreaks/100))
The answer is now 80.22%
. (A or B)
returns A, if A cannot be deduced to be false, otherwise B. A list of all 0s
isn't False
. So you were only checking for streaks of 0s
.