I want to generate a list of all permutations of a string using a backtracking algorithm.
I modified some code from a previous post: https://stackoverflow.com/a/20955291/12021192
def permutations(string, step = 0):
permTrack = []
if step == len(string):
permTrack.append(''.join(string))
for i in range(step, len(string)):
string_copy = list(string)
string_copy[step], string_copy[i] = string_copy[i], string_copy[step]
permutations(string_copy, step + 1)
return permTrack
permTrack = permutations('ABC')
I expected permTrack = ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA]
, but the actual output is permTrack = [ ]
.
The idea is to is to append to a list permTrack at the base case, when step == len(string). This works for instance in the original code to print the permutations.
Can someone help me figure this out?