[英]How does the inner loop append on each iteration?
def per1(seq):
if not seq:
return [seq]
else:
res=[]
for i in range(len(seq)):
rest=seq[:i]+seq[i+1:]
for x in per1(rest):
res.append(seq[i:i+1]+x)
return res
print(per1('abc'))
The function is to print a permuted list of sequence but I am not sure how the inner for loop is working. 该功能是打印序列的排列列表,但我不确定内部for循环的工作方式。 I have tried to use trace()
to see how the control is moving thru the loop but I couldn't figure how the loop is working the second time. 我试图使用trace()
来查看控件如何在循环中移动,但是我无法弄清楚第二次循环是如何工作的。 The first time, ' rest '
value is 'bc','c'
. 第一次, ' rest '
值是'bc','c'
。
Each time through the for i
loop, rest
is set to the input string with one character removed. 每次通过for i
循环, rest
字符都会设置为除去一个字符的输入字符串。 The first time it has the first character removed, the second time it has the second character removed, etc. seq[:i]
is every character before i
, and seq[i+1:]
is every character after i
. 第一次它具有第一个字符删除,它具有第二字符等除去第二时间seq[:i]
是前每一个字符i
,和seq[i+1:]
是后每个字符i
。
Then it calls itself recursively on rest
. 然后,它在rest
递归调用自己。 This returns all the permutations of that shorter string. 这将返回该较短字符串的所有排列。 So when rest
is "bc"
, this returns ["bc", "cb"]
. 因此,当rest
是"bc"
, "bc"
返回["bc", "cb"]
。 The for x
loop iterates through this list, and concatenates each one to seq[i:i+1]
(which is the character that was removed when creating rest
), and appends this to res
. for x
循环遍历此列表,并将每个列表连接到seq[i:i+1]
(这是创建rest
时删除的字符),并将其附加到res
。
So the first iteration of the main loop sets rest
to "bc"
, then appends "abc"
and "acb"
to res
. 因此,主回路组的第一次迭代rest
,以"bc"
,然后追加"abc"
和"acb"
到res
。
The second iteration does the same thing, with rest
set to "ac"
, and seq[i:i+1]
being the missing character "b"
, so it appends "bac"
and "bca"
to res
. 第二次迭代执行相同的操作, rest
设置为"ac"
,而seq[i:i+1]
为缺少的字符"b"
,因此将"bac"
和"bca"
追加到res
。
The third iteration is similar, with rest
set to "ab"
, so it appends "cab"
and "cba"
to res
. 第三次迭代类似, rest
设置为"ab"
,因此将"cab"
和"cba"
追加到res
。
The special situation is the base case of the recursion. 特殊情况是递归的基本情况。 If the input string is empty, we just return a list with that empty string -- an empty string has trivial permutations. 如果输入字符串为空,我们只返回带有该空字符串的列表-一个空字符串具有琐碎的排列。 When the caller does its for x
loop, it will simply concatenate this empty string onto the current letter. 当调用者执行它的for x
循环时,它将简单地将此空字符串连接到当前字母上。 This case is needed to prevent infinite recursion. 需要这种情况以防止无限递归。 You could also make the case where len(seq) == 1
the base case, since the permutations of a single letter is also trivial. 您还可以将len(seq) == 1
作为基本情况,因为单个字母的排列也是微不足道的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.