- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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'))
one oen noe neo eno eon None
- Python Program to print all permutations of a given string
- Print all permutations of a given string
- All possible permutations of N lists in Python
- Python - Generate all possible permutations of words in a Sentence
- C Program to print all permutations of a given string
- Program to find list of all possible combinations of letters of a given string s in Python
- C++ Program to Find the Number of Permutations of a Given String
- Print all distinct permutations of a given string with duplicates in C++
- All permutations of a string using iteration?
- Print all permutations of a string in Java
- Python program to get all permutations of size r of a string
- Find all possible outcomes of a given expression in C++
- How to generate all permutations of a list in Python?