繁体   English   中英

Python:可以混合使用生成器和递归函数吗?

[英]Python: is it possible to mix generator and a recursive function?

有没有办法使以下代码起作用?

add = lambda n: (yield n) or add(n+1)

(答案不必采用功能性样式)

我不确定“ yield(n)或add(n + 1)”的意图,但是递归生成器当然是可能的。 您可能需要阅读下面的链接以掌握可能的情况,特别是标题为“递归生成器”的部分。

def add(n):
    yield n
    for m in add(n+1):
        yield m

使用递归生成器,可以轻松构建复杂的回溯器:

def resolve(db, goals, cut_parent=0):
    try:
        head, tail = goals[0], goals[1:]
    except IndexError:
        yield {}
        return
    try:
        predicate = (
            deepcopy(clause)
                for clause in db[head.name]
                    if len(clause) == len(head)
        )
    except KeyError:
        return
    trail = []
    for clause in predicate:
        try:
            unify(head, clause, trail)
            for each in resolve(db, clause.body, cut_parent + 1):
                for each in resolve(db, tail, cut_parent):
                    yield head.subst
        except UnificationFailed:
            continue
        except Cut, cut:
            if cut.parent == cut_parent:
                raise
            break
        finally:
            restore(trail)
    else:
        if is_cut(head):
            raise Cut(cut_parent)

...

for substitutions in resolve(db, query):
    print substitutions

这是由递归生成器实现的Prolog引擎。 db是表示事实和规则的Prolog数据库的字典。 unify()是统一函数,它将为当前目标创建所有替代并将更改附加到跟踪中,以便以后可以撤消。 restore()执行撤消操作,is_cut()测试当前目标是否为'!',以便我们进行分支修剪。

在我看来,您的功能似乎只是未绑定序列的另一种表达方式:

n,n + 1,n + 2,....

def add(x):
    while True:
        yield x
        x+=1

for index in add(5):
    if not index<100: break ## do equivalent of range(5,100)
    print(index)

这不是递归的,但我认为这里不需要递归样式。

基于其他答案链接的递归版本,其中有生成器调用生成器,但不是递归的:

from __future__ import generators

def range_from(n):
    yield n
    for i in range_from(n+1):
        yield i

for i in range_from(5):
    if not i<100: break ## until 100 (not including)
    print i

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM