nor*_*tpy 3 python permutation
原谅我的无知.我目前有一个脑屁,无法找到解决方案.假设我有一份清单[1, 1, 0, 0].我想计算所有四位二进制数,它们恰好有两个1和两个零,如:
['0110', '0011', '0101', '1100', '1010', '1001']
Run Code Online (Sandbox Code Playgroud)
这有效:
from itertools import permutations
set([''.join(x) for x in list(permutations('0011', 4))])
Run Code Online (Sandbox Code Playgroud)
但是这会计算整个排列,然后丢弃副本.意思是,它计算了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
Run Code Online (Sandbox Code Playgroud)
结果:
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']
Run Code Online (Sandbox Code Playgroud)