Print first n distinct permutations of string using itertools in Python
Last Updated :
07 Jan, 2019
Given a string with duplicate characters allowed, print first n permutations of given string such that no permutation is repeated.
Examples:
Input : string = "abcab", n = 10
Output : aabbc aabcb aacbb ababc abacb
abbac abbca abcab abcba acabb
Input : string = "okok", n = 4
Output : kkoo koko kook okko
Approach:
Python provides an inbuilt method to find the permutations of any given sequence which is present in the itertools
package. But this method doesn’t provide unique permutations. Hence to ensure that any permutation is not repeated, we use a set and follow the below conditions:
- If the permutation is not present in the set, print it and insert it in the set. Increment the count of number of unique permutations.
- Else, move on to the next permutation.
Below is the implementation of the above approach:
from itertools import permutations
def nPermute(string, n):
strList = sorted ( list (string))
permList = permutations(strList)
i = 0
permSet = set ()
tempStr = ''
while i < n:
tempStr = ''.join(permList.__next__())
if tempStr not in permSet:
permSet.add(tempStr)
print (tempStr)
i + = 1
if __name__ = = "__main__" :
string = "ababc"
n = 10
nPermute(string, n)
|
Output:
aabbc
aabcb
aacbb
ababc
abacb
abbac
abbca
abcab
abcba
acabb
Share your thoughts in the comments
Please Login to comment...