简体   繁体   English

发出生成字符串排列列表的问题

[英]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 我从以前的帖子中修改了一些代码: 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 = [ ] . 我期望permTrack = ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA] ,但实际输出为permTrack = [ ]

The idea is to is to append to a list permTrack at the base case, when step == len(string). 想法是在step == len(string)时,在基本情况下将permTrack附加到列表中。 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. 当递归调用permutations返回的内容时,您不执行任何操作。

If you add what gets returned to permTrack , you should get what you want. 如果将返回的内容添加到permTrack ,则应该获得所需的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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