How to find all possible permutations of a given string in Python?


To find all possible permutations of a given string, you can use the itertools module which has a useful method called permutations(iterable[, r]). This method return successive r length permutations of elements in the iterable as tuples.

 In order to get all the permutations as string, you'll need to iterate over the function call and join the tuples. For example:

 >>>from itertools import permutations
>>>print [''.join(p) for p in permutations('dune')]
['dune','duen', 'dnue', 'dneu', 'deun', 'denu', 'udne', 'uden', 'unde', 'uned', 'uedn','uend', 'ndue', 'ndeu', 'nude',
 'nued', 'nedu', 'neud', 'edun', 'ednu','eudn', 'eund', 'endu', 'enud']

 If you don't want to use in built method, but create your own, you can use the following recursive solution:

 def permutations(string, step = 0):
    if step == len(string):
        # we've gotten to the end, print the permutation
        print "".join(string)
     for i in range(step, len(string)):
        # copy the string (store as array)
        string_copy = [c for c in string]
         # swap the current index with the step
        string_copy[step], string_copy[i] =string_copy[i], string_copy[step]
         # recurse on the portion of the stringthat has not been swapped yet
        permutations(string_copy, step + 1)
print (permutations ('one'))

OUTPUT

one
oen
noe
neo
eno
eon
None

Updated on: 30-Sep-2019

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements