
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Python Program to print all permutations of a given string
- Creating all possible unique permutations of a string in JavaScript
- 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
- Print all distinct permutations of a given string with duplicates in C++
- Generating all possible permutations of array in JavaScript
- Python program to get all permutations of size r of a string
- How to generate all permutations of a list in Python?
- C++ Program to Find the Number of Permutations of a Given String
- Print all permutations of a string in Java
- All permutations of a string using iteration?
- Python Program to Print All Permutations of a String in Lexicographic Order without Recursion

Advertisements