Search code examples
pythonalgorithmpermutationpython-itertools

Duplicates in list of permutations


I am using the permutations function from the itertools library to print a list of permutations for a string. In this case, it is baca. However, the output list has duplicates of each element element. Here it is:

['aabc', 'aabc', 'aacb', 'aacb', 'abac', 'abac', 'abca', 'abca', 'acab', 'acab', 'acba', 'acba', 'baac', 'baac', 'baca', 'baca', 'bcaa', 'bcaa', 'caab', 'caab', 'caba', 'caba', 'cbaa', 'cbaa']

Here is my code. It's pretty straight forward. I don't see anything in my code that would produce this behavior.

from itertools import permutations

def rearrangeWord(word):
    p = [''.join(i) for i in permutations(word) ]
    print(sorted(p))

rearrangeWord('baca')

Solution

  • multiset_permutations can find the permutations with multiple items.

    >>> from sympy.utilities.iterables import multiset_permutations
    >>> s = 'baca'
    
    
    >>> for item in multiset_permutations(s):
        print(item)
    
    
    ['a', 'a', 'b', 'c']
    ['a', 'a', 'c', 'b']
    ['a', 'b', 'a', 'c']
    ['a', 'b', 'c', 'a']
    ['a', 'c', 'a', 'b']
    ['a', 'c', 'b', 'a']
    ['b', 'a', 'a', 'c']
    ['b', 'a', 'c', 'a']
    ['b', 'c', 'a', 'a']
    ['c', 'a', 'a', 'b']
    ['c', 'a', 'b', 'a']
    ['c', 'b', 'a', 'a']