Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permutation without duplicates in Python

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?

like image 283
JoeJackJessieJames Avatar asked May 06 '17 05:05

JoeJackJessieJames


2 Answers

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],
]
like image 104
Ry- Avatar answered Nov 11 '22 18:11

Ry-


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

set(permutations(p))
like image 35
Peter Pei Guo Avatar answered Nov 11 '22 20:11

Peter Pei Guo