Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random selection of contiguous elements in an array in Python

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()

like image 655
Edmon Avatar asked Jan 16 '15 16:01

Edmon


People also ask

How do you select a random element from an array in Python?

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.

How do you randomly select data in Python?

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.

How do you select multiple random elements in a list in Python?

Use the random. choices() function to select multiple random items from a sequence with repetition.

How do I randomly select from a NumPy array?

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.


Video Answer


2 Answers

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])]
like image 128
elyase Avatar answered Oct 27 '22 14:10

elyase


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)
like image 44
Padraic Cunningham Avatar answered Oct 27 '22 14:10

Padraic Cunningham