How to sample from Cartesian product without repetition

后端 未结 5 1425
心在旅途
心在旅途 2020-12-18 13:41

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

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-18 13:54

    You can use sample from the random lib:

    import random
    [[random.sample(x,1)[0] for x in list_of_sets] for _ in range(n)]
    

    for example:

    list_of_sets = [{1,2,3}, {4,5,6}, {1,4,7}]
    n = 3
    

    A possible output will be:

    [[2, 4, 7], [1, 4, 7], [1, 6, 1]]
    

    EDIT:

    If we want to avoid repetitions we can use a while loop and collect the results to a set. In addition you can check that n is valid and return the Cartesian product for invalid n values:

    chosen = set()
    if 0 < n < reduce(lambda a,b: a*b,[len(x) for x in list_of_sets]):
        while len(chosen) < n:
            chosen.add(tuple([random.sample(x,1)[0] for x in list_of_sets]))
    else:
        chosen = itertools.product(*list_of_sets)
    

提交回复
热议问题