Producing a certain number of combinations of a certain length?

Question:

I was wondering if there was a function or algorithm that will produce only a certain number of random combinations of list elements. For example, I want 50 combinations of length 4 of a list’s elements. Is there anything I can use for this? Thanks!

Asked By: bellbottoms

||

Answers:

Use random.sample and just repeat it 50 times with a list comprehension.

import random
combinations = [random.sample(my_list, 4) for _ in range(50)]

The combinations may overlap. If you want them not to overlap (50 combinations with no shared elements), then take a single large sample and split it up into chunks.

selection = random.sample(my_list, 4 * 50)
combinations = [selection[i:i+4] for i in range(0, 4*50, 4)]
Answered By: Stuart

You can use the standard itertools.combinations function for generating combinations (note that the result is a generator). Then, you can use random.sample to randomly select nth elements of the created combinations.

Note that this solution has not a good performance if the fraction of selected combinations from total generated combinations is low (because all combinations are generated first and then selected randomly).

import itertools
import random

ELEMENTS = [1, 2, 3, 4, 5, 6, 7, 8]
COMBINATIONS_COUNT = 50
EACH_COMBINATION_LENGTH = 4

all_combinations = list(itertools.combinations(ELEMENTS, EACH_COMBINATION_LENGTH))
selected_combinations = random.sample(all_combinations, COMBINATIONS_COUNT)

print(selected_combinations)
Answered By: Alireza
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.