0
listA = ['000','001','010','011', '100','101','111','110']

To get the above list I usually use the following code. My aim is to get all the possible combinations of 3 numbers where each number can either be 0 or 1.

listA = list(range(0,222))
listA = [str(x).zfill(3) for x in listA]

 listA = [x for x in listA if not x[-3] in [str(z) for z in range(2,10,1)]]
 listA = [x for x in listA if not x[-2] in [str(z) for z in range(2,10,1)]]
 listA = [x for x in listA if not x[-1] in [str(z) for z in range(2,10,1)]]

This only works if list(range(0,222)) is relatively small, for large range like (0,222222222222), listA = list(range(0,222222222222)) returns Memory error. Is there another way to do this?

tAPOUTO
  • 13
  • 3

2 Answers2

0

You could try using itertools.product:

>>> from itertools import product
>>> a = [''.join(p) for p in product('01', repeat=3)]
>>> a
['000', '001', '010', '011', '100', '101', '110', '111']
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
0

Isn't this just binary strings from 0 to some end number?

You could do:

def zn1(up):
    w=len(f'{up:b}')
    return [f'{x:0{w}b}' for x in range(up+1)]

Or, if memory is an issue, use a generator:

def zn1(up):
    w=len(f'{up:b}')
    for n in range(up+1):
        yield f'{x:0{w}b}'

The first for example:

>>> zn1(7)
['000', '001', '010', '011', '100', '101', '110', '111']

>>> zn1(2000)
['00000000000', '00000000001', '00000000010', '00000000011', '00000000100', 
...
'11111001100', '11111001101', '11111001110', '11111001111', '11111010000']
dawg
  • 98,345
  • 23
  • 131
  • 206