Python Practice › Function Programs › Program 39
All permutations of a string
Write a Python function that returns all permutations of a string, without itertools.
Input
"abc"
Output
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Approach
- Recursion: fix each character first and permute the rest.
Solution
def permutations(text): if len(text) <= 1: return [text] result = [] for i, ch in enumerate(text): for rest in permutations(text[:i] + text[i + 1:]): result.append(ch + rest) return result print(permutations("abc"))Output
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Line by line
Lines 2-3
A string of 0 or 1 characters has one permutation.
Lines 5-7
Each character goes first, followed by every permutation of the remaining characters.
Learn the concept
New to this topic? Read the lesson, then come back.