这是我遇到问题的代码。
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/