简体   繁体   中英

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.

set("".join(seq) for seq in itertools.permutations("00011"))
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM