I have a list of sets, and I wish to sample n different samples each containing an item from each set. What I do not want is to have it in order, so, for example, I will ge
As I want no repetition, and sometimes it is not possible the code is not that short. But as @andreyF said, random.sample does the work. Perhaps there is also a better way that avoids resampling with repetition until enough non repetitive ones exist, this is the best I have so far.
import operator
import random
def get_cart_product(list_of_sets, n=None):
max_products_num = reduce(operator.mul, [len(cluster) for cluster in list_of_sets], 1)
if n is not None and n < max_products_num:
refs = set()
while len(refs) < n:
refs.add(tuple(random.sample(cluster, 1)[0] for cluster in list_of_sets))
return refs
return (prod for i, prod in zip(range(n), itertools.product(*list_of_sets)))
return itertools.product(*list_of_sets)
Note that the code assumes a list of frozen sets, a conversion of random.sample(cluster, 1)[0] should be done otherwise.