How to sample from Cartesian product without repetition

后端 未结 5 1412
心在旅途
心在旅途 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 14:03

    Matmarbon's answer is valid, this is a complete version with an example and some modifies for easy understanding and easy use:

    import functools
    import random
    
    def random_order_cartesian_product(factors):
        amount = functools.reduce(lambda prod, factor: prod * len(factor), factors, 1)
        print(amount)
        print(len(factors[0]))
        index_linked_list = [None, None]
        for max_index in reversed(range(amount)):
            index = random.randint(0, max_index)
            index_link = index_linked_list
            while index_link[1] is not None and index_link[1][0] <= index:
                index += 1
                index_link = index_link[1]
            index_link[1] = [index, index_link[1]]
            items = []
            for factor in factors:
                items.append(factor[index % len(factor)])
                index //= len(factor)
            yield items
    
    
    factors=[
        [1,2,3],
        [4,5,6],
        [7,8,9]
    ]
    
    n = 5
    
    all = random_order_cartesian_product(factors)
    
    count = 0
    
    for comb in all:
      print(comb)
      count += 1
      if count == n:
        break
    

提交回复
热议问题