python - Find unique permutation of a list binary values without generating all possibilities -
forgive ignorance. have brain fart @ moment , unable come solution. let's have list of [1, 1, 0, 0]
. want calculate 4 digits binary numbers have 2 1s , 2 zeros, like:
['0110', '0011', '0101', '1100', '1010', '1001']
this works:
from itertools import permutations set([''.join(x) x in list(permutations('0011', 4))])
but calculate entire permutations , discards duplicate. meaning, calculates 24 times need 6. more significant if collection [1, 1, 1, 1, 0, 0, 0, 0]
.
this should easy can't wrap head around it.
use itertools.combinations()
find possible positions ones, construct numbers using positions:
def binary(length=4, ones=2): result = [] positions in combinations(range(length), ones): result.append("".join("1" if _ in positions else "0" _ in range(length))) return result
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']