Finding All Possible Permutations of a Given String in Python
The task of generating all feasible permutations of a given input string has a straightforward solution in Python. To embark on this task, we initially consider the input string, which we shall attempt to reorder. For illustration, let's take the string 'stack' as an example:
x = 'stack'
Our goal is to create permutations of 'stack' by rearranging its characters.
l=['stack','satck','sackt'.......]
Traditionally, one might consider iterative approaches to solve this challenge, involving the random selection and transposition of pairs of characters to generate new permutations. However, we can simplify our task by utilizing the permutations() method provided by the itertools module. As its documentation suggests:
itertools.permutations(iterable[, r])
Return successive r length permutations of elements in the iterable.
Using this method in our scenario requires that we adhere to the following considerations:
Therefore, to obtain our desired permutations, we employ the following approach:
from itertools import permutations
perms = [''.join(p) for p in permutations('stack')]
This approach yields the following permutations:
['stack', 'stakc', 'stcak', 'stcka', 'stkac', 'stkca', 'satck', 'satkc', 'sactk', 'sackt', 'saktc', 'sakct', 'sctak', 'sctka', 'scatk', 'scakt', 'sckta', 'sckat', 'sktac', 'sktca', 'skatc', 'skact', 'skcta', 'skcat', 'tsack', 'tsakc', 'tscak', 'tscka', 'tskac', 'tskca', 'tasck', 'taskc', 'tacsk', 'tacks', 'taksc', 'takcs', 'tcsak', 'tcska', 'tcask', 'tcaks', 'tcksa', 'tckas', 'tksac', 'tksca', 'tkasc', 'tkacs', 'tkcsa', 'tkcas', 'astck', 'astkc', 'asctk', 'asckt', 'asktc', 'askct', 'atsck', 'atskc', 'atcsk', 'atcks', 'atksc', 'atkcs', 'acstk', 'acskt', 'actsk', 'actks', 'ackst', 'ackts', 'akstc', 'aksct', 'aktsc', 'aktcs', 'akcst', 'akcts', 'cstak', 'cstka', 'csatk', 'csakt', 'cskta', 'cskat', 'ctsak', 'ctska', 'ctask', 'ctaks', 'ctksa', 'ctkas', 'castk', 'caskt', 'catsk', 'catks', 'cakst', 'cakts', 'cksta', 'cksat', 'cktsa', 'cktas', 'ckast', 'ckats', 'kstac', 'kstca', 'ksatc', 'ksact', 'kscta', 'kscat', 'ktsac', 'ktsca', 'ktasc', 'ktacs', 'ktcsa', 'ktcas', 'kastc', 'kasct', 'katsc', 'katcs', 'kacst', 'kacts', 'kcsta', 'kcsat', 'kctsa', 'kctas', 'kcast', 'kcats']
If we encounter duplicates in our permutations, we can handle them by restructuring our data into a format that prevents duplicates, such as a set:
perms = [''.join(p) for p in permutations('stacks')]
len(perms) # 720
len(set(perms)) # 360
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3