Python Program to print all permutations of a given string

Python Program to print all permutations of a given string;  In this Python lesson, we’ll show you two different approaches for utilizing either a built-in module or a standalone module to detect and output permutations of a given string in Python.

Before we share with you a Python program to find every variant of the supplied string. Python’s itertools module is something you should be familiar with because it may be used to find all possible combinations of a given string.

permutation: As we are all aware, a permutation is a means to arrange the components of a group or set in a particular arrangement that creates a different group.

Python Program to print all permutations of a given string

  • 1: Find all permutations of a string in Python
  • 2: Python Program to Print all Permutations of a Given String without using Built-in Function

1: Find all permutations of a string in Python

Use the folloiwng steps and write a python program to print all permutations of a given string:

  • First of all, import the permutation function from the python itertools module in program.
  • Allow user to input the string and assign it in a variable.
  • 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.
  • At end of program, Print it which is our possible permutations.
# 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']

2: Python Program to Print all Permutations of a Given String without using Built-in Function

# 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