1

I am trying to generate an array of all combinations of an array, but how can I generate without repeating.

My first solution was just remove the repeating elements using some for, but I am dealing with big arrays, with 50 length size or more and the execution never end.

ex: (0,0,1,0)

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

3 Answers 3

3

If your array is really just 0s and 1s, another possibility is to use itertools.combinations to determine, where the 1s are in every combination. Example:

from itertools import combinations

array = [0,0,1,1,0,1,0,1,0,0,1,0,1,0,1]
n = len(array)
k = sum(array)

for comb in combinations(range(n), k): # Any combination to chose k numbers from range 0..n
    next_arr = [1 if i in comb else 0 for i in range(n)]
    print(next_arr)
Sign up to request clarification or add additional context in comments.

Comments

0

for your example with 4 spaces

you can represent from 0(0000) up to 2**4-1 or 15 (1111)

so you can make all the binary combos with

arrays = [list(f"{i:04b}") for i in range(2**4)]

Comments

0

Use itertools.permutations, store results in a set (as itertools.permutations treats elements as unique based on their position, not on their value).:

>>> from itertools import permutations
>>> set(permutations([0,0,1,0]))
{(0, 0, 1, 0), (1, 0, 0, 0), (0, 0, 0, 1), (0, 1, 0, 0)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.