Finding All Permutations of a Given String in Python [Duplicate]
In Python, finding all possible permutations of a given string poses a challenge. One approach involves iteration through the list of characters, transposing pairs at random to generate new strings. However, this approach has its limitations.
Optimal Solution Using itertools Module
A more efficient solution lies in the itertools module, which provides the permutations() method. This method returns successive permutations of elements in an iterable. If no argument is specified, the method defaults to generating all full-length permutations in lexicographic order.
<code class="python">import itertools x = 'stack' perms = [''.join(p) for p in permutations(x)]</code>
This code will produce a list of strings containing all possible permutations of the characters in 'stack', as follows:
perms = ['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 you encounter duplicates, consider using a set to eliminate them:
<code class="python">x = 'stack' perms = set([''.join(p) for p in permutations(x)])</code>
The above is the detailed content of How can I efficiently find all permutations of a string in Python, especially if I need to avoid duplicates?. For more information, please follow other related articles on the PHP Chinese website!