Choose at random from combinations

后端 未结 3 1185
执笔经年
执笔经年 2020-12-01 21:28

I can make a list of all combinations using list(itertools.combinations(range(n), m)) but this will typically be very large.

Given

3条回答
  •  旧巷少年郎
    2020-12-01 21:57

    From http://docs.python.org/2/library/itertools.html#recipes

    def random_combination(iterable, r):
        "Random selection from itertools.combinations(iterable, r)"
        pool = tuple(iterable)
        n = len(pool)
        indices = sorted(random.sample(xrange(n), r))
        return tuple(pool[i] for i in indices)
    

提交回复
热议问题