views:

105

answers:

2

I have a list with length N and each element of this list are 0 or 1. I need to get all possible combinations of this list. Here is my code:

def some(lst):
    result = []
    for element in lst:
        c1 = copy.copy(element)
        c2 = copy.copy(element)
        c1.append(0)
        c2.append(1)
        result.append(c1)         
        result.append(c2)
    return result

def generate(n):
   if(n == 1):
       return [[0], [1]]
   else:
        return some(generate(n - 1))    

print generate(4)

I think there is a more pythonic solution of this task. Thanks in advance.

+5  A: 

Don't they look like bit patterns (0000 ....1111 ) i.e binary bits. And all possible combination of n binary bits will range from 0 to 2**n -1

noOfBits = 5
for n in range(2**noOfBits):
    binVal = bin(n)[2:].zfill(noOfBits)
    b = [ x for x in binVal]
    print b

Do we need combinatorics for this purpose?

Output:

['0', '0', '0', '0', '0']
['0', '0', '0', '0', '1']
['0', '0', '0', '1', '0']
['0', '0', '0', '1', '1']
['0', '0', '1', '0', '0']
['0', '0', '1', '0', '1']
.......
pyfunc
Small correction: change `range(0, 2**noOfBits -1)` to `range(2**noOfBits)`.
Sheldon L. Cooper
@Sheldon L. Cooper: +1 Thanks a lot, I will edit my answer to correct that
pyfunc
Thanks. That is all I need.
demas
+3  A: 

The itertools module has ready generators for many combinatoric tasks. For your task:

list(itertools.product(*noOfBits * ((0, 1),)))
Beni Cherniavsky-Paskin