在不生成所有可能性的情况下,查找列表二进制值的唯一排列


请原谅我的无知。我现在脑子里有个屁,无法想出解决办法。假设我有一个[1, 1, 0, 0]的列表。我想计算所有有两个1和两个0的四位数二进制数,比如:
['0110', '0011', '0101', '1100', '1010', '1001']

这项工作:

from itertools import permutations
set([''.join(x) for x in list(permutations('0011', 4))])

但这会计算整个排列,然后丢弃重复的排列。意思是,它计算了24次,但我只需要6次。如果集合是[1, 1, 1, 1, 0, 0, 0, 0],则意义更大。

这应该很容易,但我就是无法理解。

使用itertools.combinations()为您的位置找到所有可能的位置,然后使用这些位置构造数字:

def binary(length=4, ones=2):
result = []
for positions in combinations(range(length), ones):
result.append("".join("1" if _ in positions else "0" for _ in range(length)))
return result

结果:

In [9]: binary()
Out[9]: ['1100', '1010', '1001', '0110', '0101', '0011']
In [10]: binary(5)
Out[10]:
['11000', '10100', '10010', '10001', '01100', '01010', '01001', '00110', '00101', '00011']
In [11]: binary(4,1)
Out[11]: ['1000', '0100', '0010', '0001']
In [12]: binary(4,4)
Out[12]: ['1111']

这篇文章有点晚了
@Tim Pietzcker的回答很好,但append中的一个内部循环对我来说很难消化;

所以我用一种简单的方式写同样的东西,速度大约快4-7倍。

def binary(length=4, ones=2):
result = []
rr = ['0'] * length  ## initialize empty list with ZEROS of given length
for c in itertools.combinations(range(length), ones):
r = rr[:] ## create a copy of initialized list
for x in c:
r[x] = '1' ## Change ZERO to ONE based on different combinations of positions 
result.append("".join(r))
return result

最新更新