- A+

Category：Languages

Please, how can I get all these binary permutations, but without repetition in Python?

` a = list(itertools.permutations([1, 1, 0, 0])) for i in range(len(a)): print a[i] (1, 1, 0, 0) (1, 1, 0, 0) (1, 0, 1, 0) ... `

It would be great if it would be roughly efficient since I'll have to do that with a list of even 30 elements like this.

Thank you!

As @Antti said in a comment, this is equivalent to looking for `combinations`

of positions of the input list which determine which bits in the output are 1.

`from itertools import combinations def binary_permutations(lst): for comb in combinations(range(len(lst)), lst.count(1)): result = [0] * len(lst) for i in comb: result[i] = 1 yield result for perm in binary_permutations([1, 1, 0, 0]): print(perm) `

Output:

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