我无法理解这段使用递归产生排列的代码

发布于 2025-01-11 14:21:58 字数 688 浏览 0 评论 0原文

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 == 0seq == '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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

比忠 2025-01-18 14:21:58

我将尝试从归纳的角度来解释它。

令序列的长度为n。
当我们简单地返回空序列(这是唯一的排列)时,我们的基本情况是 n = 0。

如果n> 0,那么:
要定义排列,我们必须首先选择第一个元素。为了定义所有排列,显然我们必须将序列的所有元素视为可能的第一个元素。

一旦我们选择了第一个元素,我们现在需要选择其余的元素。但这与查找没有我们选择的元素的序列的所有排列相同。这个新序列的长度为n-1,因此通过归纳我们可以解决它。

稍微改变原始代码以模仿我的解释并希望使其更清晰:

def permute2(seq):
    length = len(seq)
    if (length == 0):
        # This is our base case, the empty sequence, with only one possible permutation.
        yield seq
        return

    for i in range(length):
        # We take the ith element as the first element of our permutation.
        first_element_as_single_element_collection = seq[i:i+1]
        # Note other_elements has len(other_elements) == len(seq) - 1
        other_elements = seq[:i] + seq[i+1:]
        for permutation_of_smaller_collection in permute2(other_elements):
            yield first_element_as_single_element_collection + permutation_of_smaller_collection

for x in permute2('abc'):
    print('result =',x)

希望很明显原始代码与上述代码执行完全相同的操作。

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:

def permute2(seq):
    length = len(seq)
    if (length == 0):
        # This is our base case, the empty sequence, with only one possible permutation.
        yield seq
        return

    for i in range(length):
        # We take the ith element as the first element of our permutation.
        first_element_as_single_element_collection = seq[i:i+1]
        # Note other_elements has len(other_elements) == len(seq) - 1
        other_elements = seq[:i] + seq[i+1:]
        for permutation_of_smaller_collection in permute2(other_elements):
            yield first_element_as_single_element_collection + permutation_of_smaller_collection

for x in permute2('abc'):
    print('result =',x)

Hopefully it is clear that the original code does exactly the same thing as the above code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文