Generation of Combinatorial Objects · Generating Subsets
Lesson 4
There are many ways to generate all binary sequences of length \(n\) in Python. The most natural one seems to be the following.
from itertools import product
for seq in product(range(2), repeat=4):
print(*seq, sep='', end=' ')0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
Alternatively, you can take binary representations of numbers from \(0\) to \(2^{n}-1\). n = 4
print(*[f"{i:>0{n}b}" for i in range(2 ** n)])0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
This enumeration can also be done without converting to binary: take the current string and simulate adding one to it (that is, go from right to left, replacing all ones with zeros, and change the first encountered zero to one).