python - Pythonic random list of booleans of length n with exactly k Trues -
say want list of n 0/1 elements k instances of 1. there 1 line comprehension or more pythonic way following?
def random_include(n, k): ret = [] to_include = set(random.sample([i in range(n)], k)) in range(n): if in to_include: ret.append(1) ret.append(0)
here's one-line solution.
output = sorted([1] * k + [0] * (n - k), key=lambda k: random.random())
Comments
Post a Comment