Table of Contents
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
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
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
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.
0 Comments