我无法理解这段使用递归产生排列的代码
def permute2(seq):
if not seq: # Shuffle any sequence: generator
yield seq # Empty sequence
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
# In some cases x = empty string
yield seq[i:i+1] + x # Add node at front
for x in permute2('abc'):
print('result =',x)
生成第一个结果 ('abc'
) 时,i == 0
和 seq == 'abc'
的值。然后控制流将其带到外部 for 循环的顶部,其中 i == 1,这是有道理的;然而,seq == 'bc'
,这让我完全困惑。
def permute2(seq):
if not seq: # Shuffle any sequence: generator
yield seq # Empty sequence
else:
for i in range(len(seq)):
rest = seq[:i] + seq[i+1:] # Delete current node
for x in permute2(rest): # Permute the others
# In some cases x = empty string
yield seq[i:i+1] + x # Add node at front
for x in permute2('abc'):
print('result =',x)
When yielding the first result ('abc'
) the value of i == 0
and seq == 'abc'
. The control flow then takes it to the top of the outer for loop where i == 1
, which makes sense; however, seq == 'bc'
, which completely baffles me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将尝试从归纳的角度来解释它。
令序列的长度为n。
当我们简单地返回空序列(这是唯一的排列)时,我们的基本情况是 n = 0。
如果n> 0,那么:
要定义排列,我们必须首先选择第一个元素。为了定义所有排列,显然我们必须将序列的所有元素视为可能的第一个元素。
一旦我们选择了第一个元素,我们现在需要选择其余的元素。但这与查找没有我们选择的元素的序列的所有排列相同。这个新序列的长度为n-1,因此通过归纳我们可以解决它。
稍微改变原始代码以模仿我的解释并希望使其更清晰:
希望很明显原始代码与上述代码执行完全相同的操作。
I'll try to explain it from an inductive standpoint.
Let the length of the sequence be n.
Our base case is n = 0, when we simply return the empty sequence (it is the only permutation).
If n > 0, then:
To define a permutation, we must first begin by choosing the first element. To define all permutations, obviously we must consider all elements of the sequence as possible first elements.
Once we have chosen the first element, we now need to choose the rest of the elements. But this is just the same as finding all the permutations of sequence without the element we chose. This new sequence is of length n-1, and so by induction we can solve it.
Slightly altering the original code to mimic my explanation and hopefully make it clearer:
Hopefully it is clear that the original code does exactly the same thing as the above code.