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 

Suitable:
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 

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

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

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method