开发者

List of combinations

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.ap开发者_高级运维pend(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.


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']
.......


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

list(itertools.product(*noOfBits * ((0, 1),)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜