I need to generate all possible N choose K N-bit numbers where K bits are set. The best and most concise option that I was able to come up with is extremely slow:
def kbits(n, k):
result = set()
for bits in itertools.combinations(range(n), k):
s = 0
for bit in bits:
s |= 1 << bit
result.add(s)
return result
kbits(25, 12) took 8.3s on my machine.
How can I make it faster? For example, maybe there is a way to set all the bits in bulk, without looping through all of them?