How to write a recursive function to generate all permutations of a string in Python

1 Answer

0 votes
def generate_permutation(s, l, r):
    if l == r:
        print(''.join(s))
    else:
        for i in range(l, r + 1):
            s[l], s[i] = s[i], s[l]  # swap
            generate_permutation(s, l + 1, r)
            s[l], s[i] = s[i], s[l]  # backtrack


s = list("ABC")  # convert to list 

generate_permutation(s, 0, len(s) - 1)



'''
run:

ABC
ACB
BAC
BCA
CBA
CAB

'''

 



answered Nov 5 by avibootz
...