I have a list of indexes, e.g. 0...365 and I want to select few, randomly selected without replacement, contiguous sub-regions of this list.
index = [i+1 for i in range(365) ]
#n could be 3
for i in range(n):
exclusion_regions.append( get_random_contiguous_region(index) )
Does anyone have suggestions for the implementation of get_random_contiguous_region()
Use the numpy. random. choice() function to generate the random choices and samples from a NumPy multidimensional array. Using this function we can get single or multiple random numbers from the n-dimensional array with or without replacement.
Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.
Use the random. choices() function to select multiple random items from a sequence with repetition.
choice() to select random rows from a NumPy array. Use numpy. random. choice(a, size=k, replace=False) to generate a list of k random indices without repetition from a NumPy array with a rows.
You can do:
import random
n = 3
index = [i+1 for i in range(10) ]
slices = sorted(random.sample(range(0, len(index)), 2*n))
[index[start:end] for start, end in zip(slices[::2], slices[1::2])]
We need a while loop to make sure we don't end up overlapping and you can check that the length of slice meets any other criteria, using a list comp you cannot specify different criteria: If you want random slices from roughly 5 to 15 percent of the total list size and a sample size around 30 percent:
from random import choice
from numpy import arange
index = [i + 1 for i in range(365)]
choices = []
seen = set()
ar = arange(0.05,.16, .01)
ln = len(index)
sample_size = 0
while sample_size < ln * .30:
perc = choice(ar) # get random 5, 10, 15 percent slices
size = int(ln * perc)
ch = choice(index[:-size+1]) # avoid falling off the side
rn = index[ch:ch+size]
if len(rn) == size and not seen.intersection(rn):
seen.update(rn)
choices.append(rn)
sample_size += len(rn)
print(choices)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With