-2

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]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
mpy
  • 622
  • 9
  • 23

3 Answers3

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)]
David
  • 8,113
  • 2
  • 17
  • 36
  • 2
    Hello! It seems to be that this can be achieved perfectly well without messing around with strings: just take `list(product([0, 1], repeat=3))` (and convert each tuple to a list if you really want) – Izaak van Dongen Dec 15 '19 at 11:57
  • @IzaakvanDongen Thank you, I added your solution also, very elegant 1 liner – David Dec 15 '19 at 12:11
0

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]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

You specifically asked for a "list"-output, so this answer may not help you at all.

On the other hand, you did not specify what you need it for. So if you need it for comparison, you should bee looking at another data type: Set.

Alex
  • 46
  • 4