norbertpy - 11 months ago 33

Python Question

Forgive my ignorance. I have a brain fart at the moment and unable to come up with a solution. Let's say I have a list of

`[1, 1, 0, 0]`

`['0110', '0011', '0101', '1100', '1010', '1001']`

This works:

`from itertools import permutations`

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

But this calculate the entire permutations and then discards the duplicate. Meaning, it calculates 24 times but I only need 6. It is much more significant if the collection is

`[1, 1, 1, 1, 0, 0, 0, 0]`

This should be very easy but I just can't wrap my head around it.

Answer

Use `itertools.combinations()`

to find all possible *positions* for your ones, then construct the numbers using those positions:

```
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
```

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