The probability values output by the code are seriously inconsistent with the mathematical results. I hope someone can point out my mistakes or explain the underlying principle. Thanks.
import random
number_of_streaks = 0
number_of_repetitions = 0
flipping_list = []
for experiment_number in range(1_0000):
if number_of_streaks == 6:
number_of_streaks = 0
number_of_repetitions += 1
get_value = random.randint(0, 1)
flipping_list.append(get_value)
try:
if get_value == (flipping_list[-2]):
number_of_streaks += 1
else:
number_of_streaks = 0
except IndexError:
pass
print('Chance of streak: %s%%' % (number_of_repetitions / 100))
Double counting of the streak, when already on a streak.
The variable name number_of_streaks threw me sorry. That’s the length of the current streak.
When you reach a streak of length 6, number of streaks (the length of the current streak) is reset to zero, no matter whether subsequently the streak ends on the next coin flip, or continues. The 6-streak might continue to become an even longer one.
import collections
import itertools
import random
def streak_lengths(N: int = 1_0000):
for k, group in itertools.groupby((random.randint(0,1) for _ in range(N))):
streak_length = sum(1 for __ in group)
if streak_length >= 2:
yield streak_length
streak_counter = collections.Counter(streak_lengths())
print(f"{streak_counter=}")