这与递归有关。 s是字符串“ abc”。
返回s的所有排列。因此,所需的输出为:['abc','acb','bac','bca','cab','cba']。 但是我很难理解下面的代码行:
"for perm in permute(s[:i] + s[i+1:]):"
在"s[:i] + s[i+1:]"
的第一个打印语句中,它打印出的是“ c”而不是“ bc”。我以为,由于索引i从0开始(其中i = 0且让=“ a”),因此“ s [:0] + s [o + 1:]”将变为s [1:]
应返回“ bc”,因为“ b”在索引1处,而c是最后一个字母。但是打印语句返回了“ c”。
def permute(s):
out = []
# Base Case
if len(s) == 1:
out = [s]
else:
# For every letter in string
for i, let in enumerate(s):
# For every permutation resulting from Step 2 and 3 described above
for perm in permute(s[:i] + s[i+1:]):
print('s is ' + s)
print('s[:i] + s[i+1:] is ' + str(s[:i] + s[i+1:]))
print('i is ' + str(i))
print('Current letter is ' + let)
print('Current perm is ' + perm)
# Add it to output
out += [let + perm]
print('out is ' + str(out))
print()
return out
permute('abc')
s is bc
s[:i] + s[i+1:] is c
i is 0
Current letter is b
Current perm is c
out is ['bc']
s is bc
s[:i] + s[i+1:] is b
i is 1
Current letter is c
Current perm is b
out is ['bc', 'cb']
s is abc
s[:i] + s[i+1:] is bc
i is 0
Current letter is a
Current perm is bc
out is ['abc']
s is abc
s[:i] + s[i+1:] is bc
i is 0
Current letter is a
Current perm is cb
out is ['abc', 'acb']
s is ac
s[:i] + s[i+1:] is c
i is 0
Current letter is a
Current perm is c
out is ['ac']
s is ac
s[:i] + s[i+1:] is a
i is 1
Current letter is c
Current perm is a
out is ['ac', 'ca']
s is abc
s[:i] + s[i+1:] is ac
i is 1
Current letter is b
Current perm is ac
out is ['abc', 'acb', 'bac']
s is abc
s[:i] + s[i+1:] is ac
i is 1
Current letter is b
Current perm is ca
out is ['abc', 'acb', 'bac', 'bca']
s is ab
s[:i] + s[i+1:] is b
i is 0
Current letter is a
Current perm is b
out is ['ab']
s is ab
s[:i] + s[i+1:] is a
i is 1
Current letter is b
Current perm is a
out is ['ab', 'ba']
s is abc
s[:i] + s[i+1:] is ab
i is 2
Current letter is c
Current perm is ab
out is ['abc', 'acb', 'bac', 'bca', 'cab']
s is abc
s[:i] + s[i+1:] is ab
i is 2
Current letter is c
Current perm is ba
out is ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
答案 0 :(得分:1)
这是一个烹饪实践问题。所以...
for i, let in enumerate(s):
给第一个值0 a,然后将其传递给Permute进行循环...
[0 a,1 b,2 c]这些是此时循环中的值
"for perm in permute(s[:i] + s[i+1:]):
它在您调用函数permute()时正确,它通过了bc 它将第一个值再次调用enumerate('bc')0 b,然后将其传递给... permute
[0 b,1 c]这些是此时循环中的值
"for perm in permute(s[:i] + s[i+1:]):
看看发生了什么事? 它在... c上调用permute()函数!这是我们试图达到的目标。 c是第一个烫发,因为从一开始就将len(s)== 1加上进去。绝对不是一个简单的问题。 编辑:
permute函数获取字符串s并将其分割为s的开始部分,直到i索引即s [:i],其他部分为s [i + 1:]即i + 1到字符串的末尾。因此,在i为0的bc上,它需要s [:0]空字符串和s [0 + 1:],即索引1到最后一个只是c且在其上排列的结尾。 s现在是长度1,这意味着它存储在外面。我是零abc-> bc我是零bc-> c。我是0,让= b和perm = c,那么当我= 1时,让c和perm = b。
我想到的可能会使您更好地理解此代码的东西。您应该在这样的位置添加打印语句。
# Base Case
if len(s) == 1:
print('Length is 1 s=',s)
out = [s]
我认为,因为省略了它,所以它变得很难看到何时到达需要调用置换的末尾。