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

时间:2018-07-07 17:34:49

标签: 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))

我是编程新手。有人请说出问题所在。预先感谢

2 个答案:

答案 0 :(得分:0)

与该实现方式比较,查找您的问题。

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']

答案 1 :(得分:0)

对于排列,您可以使用itertools中内置的python:

from itertools import permutations

p = []
for t in permutations('abc'):
    p.append(''.join(t))
print(p)

输出为:

['abc', 'acb', 'bac', 'bca', 'cab', 'cba']