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).
1 Answer
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
6 Comments
mnzpython
Why does it not work when the block size is 12? and is there a mathematical equation for this? and is it possible to implement this online? for example, i am in a loop and i am sampling one agent from 5 at every loop and i have a 100 loops but i want all agents to be selected every 12 steps , thanks
Jan Christoph Terasa
You can alter the code to work with a blocksize of 12, but then you have to decide how to handle the remainder of 4, because after you have taken 8 blocks, you have selected 96 random numbers, and only 4 remain. Since that is not specified in your post, I have decided to not implement anything, since there is no obvious expected way to do this. Do you want to select 100 elements, or 100 times blocksize elements? Your question suggested the former, but now I have some doubts.
mnzpython
its 100 elements, but its not a fixed thing, i want to be able to increase the number of selections from 5 to 7 to 9 and the number of elements i can generate, the blocks are only to make sure that all the options are selected in that amount of time
Jan Christoph Terasa
The function I posted has all these options, but it's still unspecified how you plan to handle the case where
total is not evenly divisible by blocksize.mnzpython
i dont understand why the "total" has to be divisible by "blocksize" , i have an experiment where i need to vary the blocksize to reach optimal blocksize
|