python codekatas solutions | Cell 9 | Cell 11 | Search

The string_permutations(s) function generates all possible permutations of a given string s and returns them in a sorted list. If the input string is empty, it returns a list containing an empty string, otherwise it recursively generates all permutations of the string.

Cell 10

def string_permutations(s):
    """Find all possible permutations of a string."""
    if not s:
        return ['']
    res = []
    for perm in string_permutations(s[1:]):
        for i in range(len(perm)+1):
            res.append(perm[:i]+s[0]+perm[i:])
    return sorted(res)

assert string_permutations('') == ['']
assert string_permutations('abc') == ['abc','acb','bac','bca','cab','cba']
print('All passed!')

What the code could have been:

python
def string_permutations(s: str) -> list[str]:
    """Find all possible permutations of a string.
    
    Args:
    s (str): The input string.
    
    Returns:
    list[str]: A list of all possible permutations of the input string.
    
    Example:
    >>> string_permutations('')
    ['']
    >>> string_permutations('abc')
    ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
    """
    
    # Base case: if the string is empty, return a list with an empty string
    if not s:
        return ['']
    
    # Recursive case: get all permutations of the string without the first character
    perms = string_permutations(s[1:])
    
    # Initialize an empty list to store the permutations with the first character
    res = []
    
    # For each permutation, insert the first character at every possible position
    for perm in perms:
        for i in range(len(perm) + 1):
            # Append the permutation with the first character inserted at position i
            res.append(perm[:i] + s[0] + perm[i:])
    
    # Return the sorted list of permutations
    return sorted(res)


assert string_permutations('') == ['']
assert string_permutations('abc') == ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
print('All passed!')

Function: string_permutations(s)

Description

Finds all possible permutations of a string s.

Parameters

Returns

A sorted list of all possible permutations of the input string.

Functionality

Example Use Cases