0

I want to create all possible lists of binary vectors until a specified length, is there a better "pythonic" way to do this?

1
0
11
10
01
00
111
110
101
100
011
010
001
000
[...]

I used a recursive function of incrementing size:

def createAllBinHelper(length):
    def createAllBin(thelist, length):
        if length == 0:
            allpossibilities.append(thelist)
        else:
            createAllBin(thelist+'1', length-1)
            createAllBin(thelist+'0', length-1)

    allpossibilities = []

    for i in range(1,length):
        createAllBin('', i)

    return allpossibilities
Nicky Feller
  • 3,539
  • 9
  • 37
  • 54

3 Answers3

1

You can combine a for loop with itertools.product.

from itertools import product

for i in range(1, 4):
    for p in product('10', repeat=i):
        print(''.join(p))

Changing the upper bound of range to n+1 will let you set the maximum length of the binary string.

This is the only current answer that produces your example output verbatim (which only matters if order matters).

Jared Goguen
  • 8,772
  • 2
  • 18
  • 36
0

Maybe something like this might interest you

maxLength = 4
L = ['']
for n in range(maxLength):
    tmp = []
    for el in L:
        tmp.append(el+'0')
        tmp.append(el+'1')
        tmp.append('')
    L = tmp
L = sorted(set(L))
print(L)

output

['', '0', '00', '000', '0000', '0001', '001', '0010', '0011', '01', '010', '0100', '0101', '011', '0110', '0111', '1', '10', '100', '1000', '1001', '101', '1010', '1011', '11', '110', '1100', '1101', '111', '1110', '1111']
Pax Vobiscum
  • 2,551
  • 2
  • 21
  • 32
0

Here is something else if you are feeling a bit bored

maxLength = 4
tmp = (2**maxLength)-1
s= ''
for n in range(1, tmp+1):
    s= ''
    while n>0:
        rem = n % 2
        n = int(n/2)
        s = s + str(rem)
    print(s)

this will give you the actual Binary combinations (without the all zeros).

Oh, yes, and output

1
01
11
001
101
011
111
0001
1001
0101
1101
0011
1011
0111
1111
Pax Vobiscum
  • 2,551
  • 2
  • 21
  • 32