Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating all permutations of 2 ones and 3 zeroes with itertools

probably basic, but couldn't find it in any other question. I tried:

print ["".join(seq) for seq in itertools.permutations("00011")]

but got lots of duplications, seems like itertools doesn't understand all zeroes and all ones are the same...

what am I missing?

EDIT:

oops. Thanks to Gareth I've found out this question is a dup of: permutations with unique values. Not closing it as I think my phrasing of the question is clearer.

like image 881
ihadanny Avatar asked Dec 30 '25 11:12

ihadanny


1 Answers

list(itertools.combinations(range(5), 2))

returns a list of 10 positions where the two ones can be within the five-digits (others are zero):

[(0, 1),
 (0, 2),
 (0, 3),
 (0, 4),
 (1, 2),
 (1, 3),
 (1, 4),
 (2, 3),
 (2, 4),
 (3, 4)]

For your case with 2 ones and 13 zeros, use this:

list(itertools.combinations(range(5), 2))

which returns a list of 105 positions. And it is much faster than your original solution.

Now the function:

def combiner(zeros=3, ones=2):
    for indices in itertools.combinations(range(zeros+ones), ones):
        item = ['0'] * (zeros+ones)
        for index in indices:
            item[index] = '1'
        yield ''.join(item)

print list(combiner(3, 2))

['11000',
 '01100',
 '01010',
 '01001',
 '00101',
 '00110',
 '10001',
 '10010',
 '00011',
 '10100']

and this needs 14.4µs.

list(combiner(13, 2))

returning 105 elements needs 134µs.

like image 187
eumiro Avatar answered Jan 01 '26 01:01

eumiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!