Signup/Sign In

Python Program for Permutation of a given string

In this tutorial, you will learn to get different permutations of a given string using an inbuilt function in Python. A permutation is simply a re-arrangement of the elements in different possible orders. Strings in Python are a sequence of characters wrapped in single, double or triple quotes. Strings are made up of characters. Permutation of a string will be the set of all possible ways in which the order of the characters of the string can be changed.

Let us look at the sample input and output of the program.

Input: "pqr"

Output: pqr prq qpr qrp rqp rpq

Input: "AB "

Output: AB BA

To solve this problem we will be using the built-in function permutations() from the itertools module. Python's itertools is a module that provides various functions that work on iterators to produce complex iterators. . The permutations() method takes a list, dictionary, tuple, or other iterators as a parameter and returns the permutations of that list.

We can use this method to return a list of all possible permutations of a string. To get the result in string format we will use the join() method. It will join the list elements together to form a string.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Import permutations from itertools package

Step 2- Declare a function that accepts a string

Step 3- In the function, pass the string to the permutations() method

Step 4- Value from the method will be stored in a variable

Step 5- Print the list elements as strings

Step 6- Declare string, call function and print the value

Python Program

Look at the program to understand the implementation of the above-mentioned approach. To use permutations() method, we have to import this function from the itertools module. This method returns a list of all possible permutations of characters in the string.

# permutations in string
from itertools import permutations  
def allPermutations(s):
       
     # all permutations of string 
     permList = permutations(s)
  
     # print all permutations
     for perm in list(permList):
         print (''.join(perm))
        
s= 'DEF'
allPermutations(s)


DEF
DFE
EDF
EFD
FDE
FED

Conclusion

In this tutorial, we have seen how to use an inbuilt function from the itertools module to find different permutations of a string.