Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Permutation of a given string using the inbuilt function in Python
In this tutorial, we will find the permutation of a string using Python's built-in permutations() function from the itertools module. A permutation is a rearrangement of all characters in a string where each character appears exactly once.
How It Works
The itertools.permutations() method generates all possible arrangements of the input string's characters and returns them as tuples in an iterator object.
Step-by-Step Process
- Import the
itertoolsmodule - Initialize the string
- Use
itertools.permutations()to generate all permutations - Convert the iterator to a list of tuples
- Join each tuple to form readable strings
Example
Let's see how to find all permutations of a string ?
# importing the module
import itertools
# initializing a string
string = "XYZ"
# itertools.permutations method
permutation_list = list(itertools.permutations(string))
# printing the obj in list
print("-----------Permutations Of String In Tuples----------------")
print(permutation_list)
# converting the tuples to string using 'join' method
print("-------------Permutations In String Format-----------------")
for tup in permutation_list:
print("".join(tup))
-----------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
Understanding the Output
For a string of length n, there are n! (factorial) permutations. In our example with "XYZ" (3 characters), we get 3! = 6 permutations.
Alternative Approach
You can directly convert permutations to strings without storing intermediate tuples ?
import itertools
string = "ABC"
# Direct conversion to strings
permutations = [''.join(p) for p in itertools.permutations(string)]
print("All permutations:", permutations)
print("Total permutations:", len(permutations))
All permutations: ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] Total permutations: 6
Conclusion
The itertools.permutations() function provides an efficient way to generate all permutations of a string. It returns tuples that can be easily converted to strings using the join() method for readable output.
