gpt4 book ai didi

Python:如何制作递归生成器函数

转载 作者:太空狗 更新时间:2023-10-30 00:22:03 26 4
gpt4 key购买 nike

我一直致力于为生物学问题生成所有可能的子模型。我有一个工作递归来生成我想要的所有子模型的大列表。然而,列表很快变得难以管理(N=12 在下面的示例中是可能的,N>12 使用太多内存)。所以我想使用 yield 将其转换为生成器函数,但我被卡住了。

我的工作递归函数如下所示:

def submodel_list(result, pat, current, maxn):
''' result is a list to append to
pat is the current pattern (starts as empty list)
current is the current number of the pattern
maxn is the number of items in the pattern
'''
if pat:
curmax = max(pat)
else:
curmax = 0
for i in range(current):
if i-1 <= curmax:
newpat = pat[:]
newpat.append(i)
if current == maxn:
result.append(newpat)
else:
submodel_generator(result, newpat, current+1, maxn)

result = []
submodel_list(result, [], 1, 5)

这为我提供了预期的子模型列表。

现在,我想使用递归获得相同的列表。天真地,我以为我可以将我的 result.append() 换成一个 yield 函数,其余的就可以正常工作了。所以我尝试了这个:

def submodel_generator(pat, current, maxn):
'''same as submodel_list but yields instead'''
if pat:
curmax = max(pat)
else:
curmax = 0
for i in range(current):
print i, current, maxn
if i-1 <= curmax:
print curmax

newpat = pat[:]
newpat.append(i)
if current == maxn:
yield newpat
else:
submodel_generator(newpat, current+1, maxn)

b = submodel_generator([], 1, 5)
for model in b: print model

但现在我一无所获。一个(非常愚蠢的)挖掘告诉我函数一次到达最后的 else 语句,然后停止——即递归不再有效。

有没有办法将我的第一个笨拙的列表制作函数变成一个简洁的生成器函数?我在这里错过了什么愚蠢的东西吗?非常感谢所有帮助!

最佳答案

你应该改变这个:

submodel_generator(newpat, current+1, maxn)

为此:

for b in submodel_generator(newpat, current+1, maxn):
yield b

这将从对函数的连续调用中递归地产生值。

[更新]:请注意,从 Python 3.3 开始,您可以使用新的 yield from语法:

yield from submodel_generator(newpat, current+1, maxn)

关于Python:如何制作递归生成器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8407760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com