Q:

Find all permutations of a given string in Python

belongs to collection: Python String Programs

0

Python itertools Module

"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.

Algorithm to solve the problem:

  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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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']

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Write a function to find sum of two integ... >>
<< Python program for adding given string with a fixe...