The Wayback Machine - https://web.archive.org/web/20240118181859/https://www.geeksforgeeks.org/print-first-n-distinct-permutations-of-string-using-itertools-in-python/
Open In App
Related Articles

Print first n distinct permutations of string using itertools in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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:




# Python3 program to print first n unique 
# permutations of the string using itertools
from itertools import permutations
  
# Function to print first n unique 
# permutation using itertools 
def nPermute(string, n): 
  
    # Convert the string to list and sort 
    # the characters in alphabetical order
    strList = sorted(list(string))
      
    # Create an iterator
    permList = permutations(strList)
  
    # Keep iterating until we 
    # reach nth unique permutation
    i = 0
    permSet = set()
    tempStr = '' 
      
    while i < n:
        tempStr = ''.join(permList.__next__())
          
        # Insert the string in the set
        # if it is not already included
        # and print it out.
        if tempStr not in permSet:
            permSet.add(tempStr)
            print(tempStr)
            i += 1
      
# Driver code 
if __name__ == "__main__":
  
    string = "ababc"
    n = 10
    nPermute(string, n) 


Output:

aabbc
aabcb
aacbb
ababc
abacb
abbac
abbca
abcab
abcba
acabb

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 07 Jan, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials