Python permutations of x unique characters are repeated y times each

I am trying to get a permutation list of x unique characters repeating y times each. So it looks something like this:

x = ['0', '1']
y = 2

permutation_list = ['0011','0101','1001','1010','0110','1100']

I do not want unnecessary things ('0001', '1110', etc.), and I do not want duplicates - does anyone know how to do this?

I tried using itertools, but in the end I got duplicates.

+4
source share
1 answer

Use all the unique permutations on your list by repeating yonce:

from itertools import permutations

permutation_list = set(permutations(x * y))

Demo:

>>> from itertools import permutations
>>> x = ['0', '1']
>>> y = 2
>>> set(permutations(x * 2))
{('0', '1', '1', '0'), ('0', '1', '0', '1'), ('1', '0', '1', '0'), ('1', '1', '0', '0'), ('1', '0', '0', '1'), ('0', '0', '1', '1')}

They can be displayed back to the list:

[''.join(combo) for combo in set(permutations(x * 2))]
+6
source

All Articles