I can make a list of all combinations using list(itertools.combinations(range(n), m))
but this will typically be very large.
Given
n
andm
, how can I choose a combination uniformly at random without first constructing a massive list??
Advertisement
Answer
From http://docs.python.org/2/library/itertools.html#recipes
JavaScript
x
7
1
def random_combination(iterable, r):
2
"Random selection from itertools.combinations(iterable, r)"
3
pool = tuple(iterable)
4
n = len(pool)
5
indices = sorted(random.sample(xrange(n), r))
6
return tuple(pool[i] for i in indices)
7