Home > OS >  generate random sample with in a range but with different size each time in python
generate random sample with in a range but with different size each time in python

Time:12-07

Ex: Assume we have [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13] for the first sample we will select [3, 4, 5, 9, 1, 2] and for the second sample [7, 9, 1, 4, 5, 6, 2] and so on Make sure each sample will have at least 3 elements

CodePudding user response:

Don't ask people to write code for you on SO.

With that said:

import random
def select_sample(arr,minsize):
    size = random.randrange(minsize,len(arr))
    return [random.choice(arr) for i in range(size)]

CodePudding user response:

Consider utilizing random.sample:

from random import sample


def generate_n_samples_different_sizes(population: list, min_sample_size: int,
                                       num_samples: int) -> list[list[int]]:
    pop_size = len(population)
    sample_sizes = sample(range(min_sample_size, pop_size   1), k=num_samples)
    return [
        sample(population, k=sample_size)
        for sample_size in sorted(sample_sizes) # removed sorted if increasing sample sizes is not required
    ]


n_samples_different_sizes = generate_n_samples_different_sizes(
    population=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
    min_sample_size=3,
    num_samples=4)

print(n_samples_different_sizes)

Example Output:

[[7, 1, 10], [7, 11, 5, 6, 12], [6, 9, 8, 1, 10, 5, 4, 3, 2, 11, 13, 7], [2, 12, 8, 4, 10, 5, 11, 6, 7, 1, 3, 9, 13]]
  • Related