Permutation of a given string using the inbuilt function in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to find the permutation of a string using the inbuilt function of Python called permutations. The method permutations is present in the itertools module.

Procedure To Find The Permutation Of A String

  • Import the itertools module.
  • Initialize the string.
  • Use the itertools.permutations method to find the permutation of the string.
  • In the third step, the method returns an object and convert it into a list.
    • List contains a permutation of string as tuples.

Example

Let's see the program.

## importing the module
import itertools
## initializing a string
string = "XYZ"
## itertools.permutations method
permutaion_list = list(itertools.permutations(string))
## printing the obj in list
print("-----------Permutations Of String In Tuples----------------")
print(permutaion_list)
## converting the tuples to string using 'join' method
print("-------------Permutations In String Format-----------------")
for tup in permutaion_list:
   print("".join(tup))

Output

If you run the above program, you will get the following result.

-----------Permutations Of String In Tuples----------------
[('X', 'Y', 'Z'), ('X', 'Z', 'Y'), ('Y', 'X', 'Z'), ('Y', 'Z', 'X'), ('Z', 'X', 'Y'), ('Z', 'Y', 'X')]
-------------Permutations In String Format-----------------
XYZ
XZY
YXZ
YZX
ZXY
ZYX

If you have any doubts regarding the program, please do mention them in the comment section.

raja
Published on 27-Aug-2019 11:32:22
Advertisements