Is there a function to return all 3 digit combination of 1 and 0 in lists? The desired output should look like below:
[0,0,0]
[1,0,0]
[0,1,0]
[0,0,1]
[1,1,0]
[1,0,1]
[0,0,1]
[1,1,1]
Is there a function to return all 3 digit combination of 1 and 0 in lists? The desired output should look like below:
[0,0,0]
[1,0,0]
[0,1,0]
[0,0,1]
[1,1,0]
[1,0,1]
[0,0,1]
[1,1,1]
you can do the following:
from itertools import product
def split_str(s):
return [int(ch) for ch in s]
k=3
mm = []
m = ["".join(seq) for seq in product("01", repeat=k)]
mm = list(map(split_str, m))
print(mm)
The result is:
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
Other solution suggested by Izaak van Dongen:
mm2 = list(product([0, 1], repeat=3))
print(mm2)
Will result in the following output (that its easily can by "untupled"):
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
If you don't want to import itertools
, you can do this:
n = 3
for i in range(0, 2**n):
print([*map(int, '{:0{n}b}'.format(i, n=n))])
Prints:
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]