Reputation: 2797
How to find number of permutations when items are repeated?
For example, for the string aab
I want the following output: aab
, aba
, baa
.
Upvotes: 1
Views: 2077
Reputation: 20801
more-itertools.distinct_permutations(iterable)
Yields successive distinct permutations of the elements in iterable.
Equivalent to
set(permutations(iterable))
, except duplicates are not generated and thrown away. For larger input sequences, this is much more efficient.
from more_itertools import distinct_permutations
for p in distinct_permutations('aab'):
print(''.join(p))
# baa
# aba
# aab
Installation:
pip install more-itertools
Upvotes: 2
Reputation: 1061
You can use the standard-library itertools module:
from itertools import permutations
iterable = "aab"
print(set(permutations(iterable, len(iterable))))
By executing that code, I get the following output:
None@vacuum:~$ python3.6 ./test.py
{('b', 'a', 'a'), ('a', 'b', 'a'), ('a', 'a', 'b')}
Upvotes: 2
Reputation: 8781
The following should work:
import itertools
set(itertools.permutations('aab'))
The permutations
will produce all permutations, but it will repeat some of it's output because it can't differentiate between a1 a2 b
and a2 a1 b
. Here a1
is the first occurrence of a
, and a2
the second. So you need to just keep the unique elements, and a set
is a good way to do that, as the constructor transforms the input iterable into a unique collection.
Upvotes: 0