 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
                    