为什么要“产量”递归功能

发布于 2025-01-23 02:42:43 字数 427 浏览 3 评论 0原文

当我尝试实现置换函数时,我从Web获得了此代码。

def permutations(seq):    
    if len(seq) == 1:
        yield seq
    else:
        for i in range(len(seq)):
            perms = permutations(seq[:i] + seq[i+1:])
            for p in perms:
                yield [seq[i], *p]

我试图解开代码,但失败了,因为我不了解如何递归使用屈服。我知道每次下一个(生成器)时,它都会在身体中运行代码,并在收益率上停止。但是,如果我只有一次只做一次才能达到基本状态,这很明显,我必须多次进行递归才能到达基地(len == 1)。 根据我的理解,底线的产量应返回。

When I try to implement a permutation function, I got this code from web.

def permutations(seq):    
    if len(seq) == 1:
        yield seq
    else:
        for i in range(len(seq)):
            perms = permutations(seq[:i] + seq[i+1:])
            for p in perms:
                yield [seq[i], *p]

I tried to unserstand the code but I failed, because I can't understand how to use yield recursively. I know every time I do next(generator), It run the code in body and stop at a yield statement. But how can it reach base condition if I only do next once cause it's obvious I have to do recursion multiple times before I can reach base(len == 1).
Based on my understanding, the yield from the bottom line should be return.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

究竟谁懂我的在乎 2025-01-30 02:42:43

此作用的原因如下:在条件的递归分支的环体中,首先要执行:

            perms = permutations(seq[:i] + seq[i+1:])

这在当前递归步骤中创建本地生成器对象。

接下来的两行:

            for p in perms:
                yield [seq[i], *p]

迭代该发电机对象生成的所有值,并根据它们产生排列。

收益率语句不会“穿透”递归,但是您的代码收集了从递归调用中产生的值,然后根据它们产生结果。

实际上,这里有很多屈服 - 与seq的长度成正比,但是根据输出的大小,这是可以预期的。

The reason this works is as follows: in the loops body of the recursive branch of the condition, first you perform:

            perms = permutations(seq[:i] + seq[i+1:])

This create a local generator object within the current recursion step.

The next two lines:

            for p in perms:
                yield [seq[i], *p]

iterate over all the values generated by that generator object, and yields permutation based on them.

The yield statement does not "penetrate" recursion, but your code collects the value yielded from a recursive call, and then yields results based on them.

There is in fact a lot of yielding going on here - proportional to the factorial of the length of seq, but that would be expected, based on the size of your output.

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