python - 生成字符串代码错误的排列

标签 python algorithm permutation

这是我遇到问题的代码。

def permute(word):
    letters = list(word)
    print(type(letters))
    for letter in letters:
        letter_copy = letters.remove(letter)
        rtrn_list = letter + permute(letter_copy)
    return rtrn_list

w = 'ABC'
print(permute(w))

我是编程新手。有人请说问题出在哪里。提前致谢

最佳答案

与此实现进行比较,找出您的问题。

def permute(string):
        '''
        Recursively finds all possible combinations of the
        elements -- or permuations -- of an input string and
        returns them as a list.
        >>>permute('abc')
        ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
        '''
        output = []
        if len(string) == 1:
            output = [string]
        else:
            for i, let in enumerate(string):
                for perm in permute(string[:i] + string[i + 1:]):
                    #print('Let is', let)
                    #print('Perm is', perm)
                    output += [let + perm]
        return output

permute('abc')
Out[ ]:
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

关于python - 生成字符串代码错误的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51225496/

相关文章:

python - xmpppy 和 Facebook 聊天集成

python - 打印文件/列表中相同值的索引

python - 如何在python中将天转换为年和月?

javascript - 将数字插入已排序的数字数组的有效方法?

algorithm - 统一成本搜索项目 euler #81

python - 找到可以重新排列序列的方式的数量

arrays - 带重复的部分排列。列出所有解决方案算法

python - 是否有用于将 Python 与 Hadoop 结合使用的分布式机器学习库?

在数组中查找奇数项(没有对)的算法?