Reputation: 19
I want to select a random number from 0 to 5 a hundred times (in a loop) with the condition that every 10 times all the numbers be selected at least once. Is there a function that can do this? or a specific library? How should I go about making it happen? (the important part is to make sure all the options are selected in a given specific time).
Upvotes: 0
Views: 254
Reputation: 5945
Draw ten numbers, and repeat drawing random numbers until the condition is fulfilled, then move on to the next block of ten. You can easily check whether you got all numbers by comparing the set
of drawn numbers to the set
of the desired range. Do note that random.randrange
excludes the upper limit of 5
, i.e. it samples integers from [lower, upper).
import random
def random_blocks(lower=0, upper=5, total=100, blocksize=10):
if total % blocksize:
raise ValueError("total has to be evenly divisible by blocksize")
if upper - lower > blocksize:
raise ValueError("blocksize has to be greater than or equal to (upper - lower)")
cond = set(range(lower, upper))
valid = []
while len(valid) < total:
temp = [random.randrange(lower, upper) for _ in range(blocksize)]
if set(temp) == cond:
valid.extend(temp)
return valid
Upvotes: 1