Lets say I have the following word : "aabb" then all possible unique permutations are : "aabb","abab","baba","abba","baab" and "bbaa". Notice that that there are not 4! = 24 ways to do so but 4 choose 2 = 6. What I currently have is a naive approach : finding all permutations, including the duplicates, and afterwards deleting the duplicates :
def permutations(l):
if len(l) <=1:
yield l
else:
for p in permutations(l[1:]):
for i in range(len(l)):
yield p[:i] + l[0] + p[i:]
print(set(permutations("aabb")))
My question is if their exists a more efficient way to find all these permutations?
EDIT : i do NOT want an approach which follows the inefficient idea of finding all permutations and afterwards deleting the duplicates. My code sample does this already!
EDIT : coldspeed correctly marked my question as duplicate. The correct answer would be to use sympy's multiset_permutations function :
>>> from sympy.utilities.iterables import multiset_permutations
>>> list(multiset_permutations([1,1,1]))
[[1, 1, 1]]
>>> list(multiset_permutations([1,1,2]))
[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
, per @Bill Bell.