Program to print permutation of given string using Python

by | Apr 2, 2021 | Python Programs

Home » Python » Python Programs » Program to print permutation of given string using Python

Introduction

The task is to find the permutation of the given string. A permutation is a collection of elements of a set having different order or placement.

Expression: n digits have n! combinations

Program to print permutation of given string 

 

Program

Case 1: String with no duplicate character

from itertools import permutations




def perm_str(x):

# Using permuatstion()

    lst_perm = permutations(x)

    for i in list(lst_perm):

        print(''.join(i))

       

input_str = input("Enter the string : ")

perm_str(input_str)

Output

Program to print permutation of given string Output 1 

Case 2: String with duplicate characters

from itertools import permutations
import string

def perm_str(x):
    s = string.ascii_letters
    ls_perm = permutations(x)
    dict = []
    for i in list(ls_perm):
# Print string not present in d
        if (i not in dict):
            dict.append(i)
            print(''.join(i))
        
input_str = input("Enter the string : ")
perm_str(input_str)

Output

Program to print permutation of given string Output 2

Explanation

Python provides an in-built function permutations(). In case 1, we have printed all the permutations using join() function whereas, in case 2, we have created an empty dictionary and appended the permutation strings when traversed to avoid the repetition.

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author