Help with probability code

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.

A streak of length 12 will be double counted.

This is how I’d do it:

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=}")

e.g.

>python streak_counter.py
streak_counter=Counter({2: 1253, 3: 611, 4: 308, 5: 151, 6: 90, 7: 35, 8: 23, 9: 5, 10: 5, 11: 3, 12: 1})

What is the code supposed to do? Are we supposed to guess that from the code that doesn’t do it?

And what are “the mathematical results” and what outputs do you get instead?

I know that problem, that’s exactly what I wanted, maybe you misunderstood what I meant.:sweat_smile: (My English isn’t good)

It seems to me Yahtzee.

I see no Yahtzee in that. To me it almost looks like the Coin Flip Streaks exercise.

Oh right. It’s only a coin flip. You have to do randint(1, 6) to get a Yahtzee.

EDIT: anyway, I think the OP was in the right direction. I suppose we’ve done a lot of worse “botched” attempts of code in our life :slight_smile:[1]


  1. Well, probably more in my life than in your :rofl: ↩︎