我一直致力于为生物学问题生成所有可能的子模型。我有一个工作递归来生成我想要的所有子模型的大列表。然而,列表很快就会变得难以管理(在下面的示例中 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 语句一次,然后停止 - 即递归不再起作用。
有没有办法将我的第一个笨重的列表制作函数变成一个漂亮整洁的生成器函数?我在这里错过了什么愚蠢的事情吗?非常感谢所有帮助!