from random import randrange k = 6 trials = 10000 totalflips = 0 # total number of flips over all trials minflips = None # smallest number of flips in a single trial maxflips = None # biggest number of flips in a single trial goal = 'H' * k for t in range(trials): history = '' count = 0 while history != goal: history += 'H' if randrange(2)==0 else 'T' history = history[-k: ] # save only the most recent k results count += 1 totalflips += count if t == 0: minflips = maxflips = count else: minflips = min(count, minflips) maxflips = max(count, maxflips) print('Average number of flips', totalflips/trials) print('Minimum number of flips', minflips) print('Maximum number of flips', maxflips)