Find all permutations of a given string in Python

Finding all permutations of a given string: Here, we are going to learn how to find all permutations for a given string by using the itertools module in Python programming language? By Bipin Kumar Last updated : February 25, 2024

"itertools" are an inbuilt module in Python which is a collection of tools for handling iterators. It is the most useful module of Python. Here, a string is provided by the user and we have to print all the possible permutations of the given string in Python. As we all know the permutation is a way of arranging the elements of a group or set in a specific order or sequence which makes a different group. We all have calculated the permutations by using the pen and paper but here we will do this by using the Python programming language in a very small time.

Problem statement

Given a string, write a Python program to find all permutations of the given string.

Algorithm

  1. Initially, we will import the permutation function from the itertools module.
  2. Take the string from the user and assign it in a variable s.
  3. Generate all permutation using the permutation function and assign it in a variable p.
  4. Since all elements of p are in tuple form. So, convert it in the list.
  5. At last, add all list elements and print it which is our possible permutations.

Let's start writing the Python program by implementing the above algorithm in a simple way.

Python program to find all permutations of a given string

# importing the module
from itertools import permutations

# input the sting
s=input('Enter a string: ')

A=[]
b=[]
p=permutations(s)

for k in list(p):
    A.append(list(k))
    for j in A:
        r=''.join(str(l) for l in j)
        b.append(r)

print('Number of all permutations: ',len(b))
print('All permutations are: ')
print(b)

Output

Enter a string: ABC
Number of all permutations: 21
All permutations are:
['ABC', 'ABC', 'ACB', 'ABC', 'ACB', 'BAC', 'ABC', 'ACB', 'BAC', 'BCA', 'ABC', 
'ACB', 'BAC', 'BCA', 'CAB', 'ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']

To understand the above program, you should have the basic knowledge of the following Python topics:

Python String Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.