Combination of 1 and 0 in an array in Python

只谈情不闲聊 提交于 2019-12-06 04:19:49

You can also use combinations to generate unique combinations directly:

n = 8
n1 = 4
for x in itertools.combinations( xrange(n), n1 ) :
    print [ 1 if i in x else 0 for i in xrange(n) ] 

[1, 1, 1, 1, 0, 0, 0, 0]
[1, 1, 1, 0, 1, 0, 0, 0]
[1, 1, 1, 0, 0, 1, 0, 0]
[1, 1, 1, 0, 0, 0, 1, 0]
...
[0, 0, 0, 1, 1, 1, 0, 1]
[0, 0, 0, 1, 1, 0, 1, 1]
[0, 0, 0, 1, 0, 1, 1, 1]
[0, 0, 0, 0, 1, 1, 1, 1]

This is more efficient than permutations because you don't iterate over unwanted solutions.

The intuition is that you're trying to find all possible ways to fit four "1"s in a sequence of length 8; that's the exact definition of combinations. That number is C(8,4)=8! / (4! * 4!) = 70. In contrast, the solution using permutations iterates over 8! = 40,320 candidate solutions.

You are producing a permutation of a multiset.

The simple but naive approach is to use itertools.permutations(), with a set to filter out repeated combinations:

>>> from itertools import permutations
>>> seen = set()
>>> for combo in permutations([1] * 4 + [0] * 4):
...     if combo not in seen:
...         seen.add(combo)
...         print combo
...
(1, 1, 1, 1, 0, 0, 0, 0)
(1, 1, 1, 0, 1, 0, 0, 0)
(1, 1, 1, 0, 0, 1, 0, 0)
(1, 1, 1, 0, 0, 0, 1, 0)
(1, 1, 1, 0, 0, 0, 0, 1)
(1, 1, 0, 1, 1, 0, 0, 0)
# ...
(0, 0, 1, 0, 1, 0, 1, 1)
(0, 0, 1, 0, 0, 1, 1, 1)
(0, 0, 0, 1, 1, 1, 1, 0)
(0, 0, 0, 1, 1, 1, 0, 1)
(0, 0, 0, 1, 1, 0, 1, 1)
(0, 0, 0, 1, 0, 1, 1, 1)
(0, 0, 0, 0, 1, 1, 1, 1)

or, producing the whole sequence in one go:

set(permutations([1] * 4 + [0] * 4))

but this loses the order that permutations produced.

The set is needed as permutations() sees the 4 1 and 4 0 as individual characters and one 1 swapped with another is considered a unique permutation.

You could also use the ordering in the sequence to avoid having to use a set:

last = (1,) * 8
for combo in permutations([1] * 4 + [0] * 4):
    if combo < last:
        last = combo
        print combo

The approach is naive in that 2n! permutations are produced where we only want (2n choose n) elements. For your case that's 40320 permutations where we only need to produce 70.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!