Change language

Print first n different permutations of a string using itertools in Python

| |

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 

Python provides a built-in method for finding permutations of any given sequence that is present in the itertools package. But this method does not provide unique permutations. Therefore, to ensure that any permutation does not repeat, we use a set and meet the following conditions:

  • If the permutation is not present in the set, print it and paste it into the set. Increase the number of unique permutations.
  • Otherwise, go to the next permutation.

Below is the implementation of the above approach:

# Python3 program to print the first and unique
# line permutations using itertools

from itertools import permutations

# Function to print the first and unique
# swap using itertools

def nPermute (string, n): 


# Convert string to list and sort

# alphabetical characters

strList = sorted ( list (string))


# Create an iterator

permList = permutations (strList)


  # Keep iterating while we

# reach the nth unique permutation

  i = 0

permSet = set ()

tempStr = ’’ 


while i & lt; n:

tempStr = ’’ .join (permList .__ next __ ())


# Insert line into set

# if not already enabled

# and print.

if tempStr not in permSet:

permSet.add (tempStr)

print (tempStr)

i + = 1

# Driver code

if __ name__ = = "__ main__" :


string = "ababc "

  n = 10

nPermute (string, n) 

Exit :

 aabbc aabcb aacbb ababc abacb abbac abbca abcab abcba acabb