1

I'm looking for a way to find all binary permutations with x amount of '1'. For example:

(length = 2) x = 1 (so: find all permutations of 1 and 0 with the length 2 which have one 1 in them)

l = ['01', '10']

x = 2 (so: find all permutations of 1 and 0 with the length 2 which have two 1 in them)

l = ['11']

so far i have this which calculates all possible permutations but i'm not sure how to 'filter' them by the '1's (especially when the size is 7 for example)

pre = list(map(''.join, itertools.product('01',repeat=2)))

i'm looking for something faster/better than my for loop which counts '1'.

1 Answer 1

2

Try this:

l=7
x=6
set(itertools.permutations([1]*x + [0]*(l-x)))

results in:

{(0, 1, 1, 1, 1, 1, 1),
 (1, 0, 1, 1, 1, 1, 1),
 (1, 1, 0, 1, 1, 1, 1),
 (1, 1, 1, 0, 1, 1, 1),
 (1, 1, 1, 1, 0, 1, 1),
 (1, 1, 1, 1, 1, 0, 1),
 (1, 1, 1, 1, 1, 1, 0)}
Sign up to request clarification or add additional context in comments.

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.