Python Program to Compute all the Permutations of the String – 2024

Hey guys, in this blog we will see a Python Program to Compute all the Permutations of the String.

Table of Contents

Example 1: Using recursion

def get_permutation(string, i=0):

    if i == len(string):   	 
        print("".join(string))

    for j in range(i, len(string)):

        words = [c for c in string]
   
        # swap
        words[i], words[j] = words[j], words[i]
   	 
        get_permutation(words, i + 1)

print(get_permutation('mlp'))

Output

mlp
mpl
lmp
lpm
plm
pml
None
  • Here we have used the concept of recursion to create all the permutations of the given string.

Example 2: Using itertools

from itertools import permutations

words = [''.join(p) for p in permutations('mlp')]

print(words)

Output

['mlp', 'mpl', 'lmp', 'lpm', 'pml', 'plm']

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

Your email address will not be published. Required fields are marked *