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
Active
Viewed 93 times
-3
-
How large is the list? – Kelly Bundy Feb 17 '22 at 11:24
-
1Do the 50 combinations have to all be different? – Kelly Bundy Feb 17 '22 at 11:25
2 Answers
1
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)]

Stuart
- 9,597
- 1
- 21
- 30
0
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)

Alireza Roshanzamir
- 1,165
- 6
- 17