Recursive String Permutations

https://www.interviewcake.com/question/python3/recursive-string-permutations

This links with one of the examples I saw in the Haskell book 202006061427, it recursively built up the permutations function.

def get_permutations(string):

    # Generate all permutations of the input string
    if len(string) in (0, 1):
        return set([string])
        
    head, tail = string[0], string[1:]
        
    return set.union(*(interleave(head, tail_perm) for tail_perm in get_permutations(tail)))
    
def interleave(char, rest_of_str):
    return {"".join((rest_of_str[:i], char, rest_of_str[i:])) for i in range(len(rest_of_str) + 1)}

uid: 202006231535 tags: #python #interviews


Date
February 22, 2023