Permutation without duplicates in Python

Question:

I have N positions, and each position can be either 0 or 1. I have fixed number of 1s, and I want to permutate these fixed number of 1s in these N positions.

from itertools import permutations
p = [0 for k in xrange(6)]
for k in xrange(0,3):
        p[k] = 1
print(list(permutations(p)))

But above result contains four [0,0,0,1,1,1] in the list. I only want one of them. How can I get rid of these duplicates?

Asked By: JoeJackJessieJames

||

Answers:

Set is perfect for this, as set does not not contain any duplicated element:

set(permutations(p))
Answered By: Peter Pei Guo

You could grab the positions of the 1s instead:

from itertools import combinations


def place_ones(size, count):
    for positions in combinations(range(size), count):
        p = [0] * size

        for i in positions:
            p[i] = 1

        yield p

In action:

>>> list(place_ones(6, 3))
[
    [1, 1, 1, 0, 0, 0],
    [1, 1, 0, 1, 0, 0],
    [1, 1, 0, 0, 1, 0],
    [1, 1, 0, 0, 0, 1],
    [1, 0, 1, 1, 0, 0],
    [1, 0, 1, 0, 1, 0],
    [1, 0, 1, 0, 0, 1],
    [1, 0, 0, 1, 1, 0],
    [1, 0, 0, 1, 0, 1],
    [1, 0, 0, 0, 1, 1],
    [0, 1, 1, 1, 0, 0],
    [0, 1, 1, 0, 1, 0],
    [0, 1, 1, 0, 0, 1],
    [0, 1, 0, 1, 1, 0],
    [0, 1, 0, 1, 0, 1],
    [0, 1, 0, 0, 1, 1],
    [0, 0, 1, 1, 1, 0],
    [0, 0, 1, 1, 0, 1],
    [0, 0, 1, 0, 1, 1],
    [0, 0, 0, 1, 1, 1],
]
Answered By: Ry-

what you are looking for is a multiset permutation.

sympy provides the function multiset_permutations:

from sympy.utilities.iterables import multiset_permutations

for perm in multiset_permutations("000111"):
    print(perm)

which outputs:

['0', '0', '0', '1', '1', '1']
['0', '0', '1', '0', '1', '1']
['0', '0', '1', '1', '0', '1']
['0', '0', '1', '1', '1', '0']
['0', '1', '0', '0', '1', '1']
['0', '1', '0', '1', '0', '1']
['0', '1', '0', '1', '1', '0']
['0', '1', '1', '0', '0', '1']
['0', '1', '1', '0', '1', '0']
['0', '1', '1', '1', '0', '0']
['1', '0', '0', '0', '1', '1']
['1', '0', '0', '1', '0', '1']
['1', '0', '0', '1', '1', '0']
['1', '0', '1', '0', '0', '1']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '1', '0', '0']
['1', '1', '0', '0', '0', '1']
['1', '1', '0', '0', '1', '0']
['1', '1', '0', '1', '0', '0']
['1', '1', '1', '0', '0', '0']
Answered By: hiro protagonist
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.