简体   繁体   中英

Issue generating a list of permutations of a string

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?

You don't do anything with what is returned by permutations when it is called recursively.

If you add what gets returned to permTrack , you should get what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM