Python Program to print all permutations of a given string

Find and print permutations of given string in python; Through this tutorial, i am going to show you how to find and print all permutations of a given string in python.

In this tutorial, i will write a program to input string and display count and print of all permutations with and without any built in function.

The permutation is a way of organizing the elements of a group or set in a specific order or sequence that forms a separate group.

Python Program to Find and Print All Permutations of a String

  • Python Program to Find, Display Count and Print All Permutations of a String
  • Python Program to Input String and Print All Permutations Without Any Built in Function

Python Program to Find, Display Count and Print All Permutations of a String

  • Import the permutation function from the python itertools module in program.
  • Get input the string and assign it in a variable in python program.
  • Use the permutation function to find all permutations and assign it in a variable.
  • Since all elements are in tuple form. So, convert it in the list.
  • Print all permutations strings.
# import the module
from itertools import permutations
# input the sting
str=input('Enter a string: ')
A=[]
b=[]
p=permutations(str)
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)

After executing the program, the output will be:

Enter a string:  cba
Number of all permutations:  21
All permutations are: 
['cba', 'cba', 'cab', 'cba', 'cab', 'bca', 'cba', 'cab', 'bca', 'bac', 'cba', 'cab', 'bca', 'bac', 'acb', 'cba', 'cab', 'bca', 'bac', 'acb', 'abc']

Python Program to Input String and Print All Permutations Without Any Built in Function

  • Create custom string conversion function.
  • Create custom function for find all Permutations string function.
  • Get input the string and assign it in a variable in python program.
  • Call find all permutations custom function.
  • Print all permutations strings.
# conversion
def toString(List):
   return ''.join(List)
   
# find all permutations
def permuteFunc(a, l, r):
   if l == r:
      print (toString(a))
   else:
      for i in range(l, r + 1):
         a[l], a[i] = a[i], a[l]
         permuteFunc(a, l + 1, r)
         a[l], a[i] = a[i], a[l] # backtracking
         
# main
str=input('Enter a string: ')
n = len(str)
a = list(str)
print("The possible permutations are:",end="\n")
permuteFunc(a, 0, n-1)

After executing the program, the output will be:

Enter a string:  abc
The possible permutations are:
abc
acb
bac
bca
cba
cab

Recommended Python Tutorials

Leave a Comment