'Create permutations then ensure each item was used at least once in Python

I have n items. Each item has an associated value to it. From the n items, I need to create k permutations of r=4 items with the constraint the associated value must be within 1 order of magnitude.

On top of that, I want to "ensure" that most of the n items are used at least once. this is where I'm struggling.

The items are rows in a dataframe What I have so far:

#random starting points
starting_points = np.random.uniform(low=min, high=max, size=(1000)).astype(float)

permutations = []

for p in starting_points:
    # filter by range
    min = p - 0.5
    max = p + 0.5
    options = items[items['value'].between(min, max)]
    if len(options) >=4:
        choices_df = options.sample(n=4)
        permutation = {}
        for i in range(4):
            permutation["id {}".format(i+1)] = choices_df['id'].iloc[i] 
        permutations.append(permutation)

I generate random starting points (1000), then define a range from which items can be chosen and sample 4 items. This works to generate about 1000 random permutations given the constraints. However, if I only need say 30 permutations how can I ensure that most of the items are chosen at least once?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source