# Code that creates a list of 100 'heads' or 'tails' values.
results.append(random.choice(('H', 'T')))
This comment is severely misleading: the code does not create a list of 100 values, it create an infinitely growing list that extends up to sampleSize
values by the time the program terminates.
Independently of the misleading comment, this is a bad idea, and can be avoided by limiting the size of the results
list in some say (del results[:-6]
, or results = results[-6:]
, I'm not sure which is better). This would also obsolete the temp
variable, because the results
array would no longer contain extra flips.
try:
temp = results[i-5:]
if temp == head_streak or temp == tail_streak:
numberOfStreaks += 1
except:
pass
Bare except
statements are a bad idea. Bare except:pass
statements even more so. Among other problems, it means that if you press Ctrl-C while your code is executing that section, the code won't exit.
It's not clear what exception you are trying to catch (results[i-5:]
doesn't throw an error if results
is less than five columnsitems long; it just truncates the list), so I can't suggest a direct replacement, but I would recommend either catching a specific exception, or removing the try-catch entirely.
Python lists natively support negative indexing, so you can simplify results[i-5:]
to results[-6:]
and remove the i
variable entirely. As suggested by the question asker in the comments, this makes the enumerate
call unnecessary.
The i
variable will then be unused. It's clearer to name variables you don't use as _
, so it's easy to tell that they aren't used.
The i
variable will then be unused. It's clearer to name variables you don't use as _
, so it's easy to tell that they aren't used.
Full code:
import random
numberOfStreaks = 0
results = []
head_streak = ['H'] * 6
tail_streak = ['T'] * 6
sample_size = 1000000
for _ in range(sample_size):
# Code that generates another 'heads' or 'tails' value
results.append(random.choice(('H', 'T')))
# Code that checks if there is a streak of 5 heads or tails in a row.
results = results[-6:]
if results == head_streak or results == tail_streak:
numberOfStreaks += 1
print('Chance of streak: %s%%' % (numberOfStreaks / sample_size))