All permutations of a string

EasyFunction Programs · 39 of 39

Write a Python function that returns all permutations of a string, without itertools.

Advertisement
Input
"abc"
Output
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Approach

  1. Recursion: fix each character first and permute the rest.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs