在Python中调用递归函数时出现问题

2024-06-01 05:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我遗漏了一些关于递归在Python中是如何工作的。我采用了以下方法来标记一个句子:

def extractIngredientInfo(ingredientLine, sectionTitle):

    print 'extractIngredientInfo' + ingredientLine

    # set-up some default values for variables that will contains the extracted datas
    usmeas             = 'N.A'
    othermeas          = 'N.A'

    p_ingredientalt     = re.compile('\(or\s(.*?)\)')
    malt = p_ingredientalt.search(ingredientLine)
    if malt:
        ingredientAlt = malt.group(1)
        ingredientLine = ingredientLine.replace(malt.group(0), '').strip()
        print 'NEW LINE TO TREAT(ALT)' + ingredientLine
        extractIngredientInfo(ingredientLine, sectionTitle)
        usmeas,othermeas = extractOneIngredientInfo(ingredientAlt)
        print 'MALT'
        ingredient 
        yield usmeas, othermeas
        #return;

    p_ingredientpurpose = re.compile('\(for\s(.*?)\)') 
    mpurpose = p_ingredientpurpose.search(ingredientLine)
    if mpurpose:
        ingredientPurpose = mpurpose.group(1)
        ingredientLine = ingredientLine.replace(mpurpose.group(0), '').strip()
        print 'NEW LINE TO TREAT(FOR)' + ingredientLine
        extractIngredientInfo(ingredientLine, sectionTitle)
        usmeas,othermeas = extractOneIngredientInfo(ingredientPurpose)
        print 'MPURPOSE'
        yield usmeas,othermeas
        #return;

    usmeas,othermeas = extractOneIngredientInfo(ingredientLine)
    print 'FINAL'
    yield usmeas, othermeas

当我调用这个函数时,我有一个匹配的malt,这将导致对递归函数extractIngredientInfo的立即调用,但这种情况从未发生(我没有看到对print 'extractIngredientInfo' + ingredientLine的第二次调用。有没有什么特别的原因没有发生?在


Tags: reforgroupprintyieldcompilemaltsectiontitle
3条回答

您的函数返回一个生成器,因为它使用yield语句。生成器将暂停,直到您请求下一个值。在

这意味着生成器函数在调用.next()或将其用作循环中的迭代器之前不会执行任何操作:

>>> def foo():
...     print 'Foo called'
...     yield 'bar'
...     print 'Still in foo'
...     yield 'baz'
... 
>>> foogen = foo()
>>> foogen.next()
Foo called
'bar'
>>> foogen.next()
Still in foo
'baz'
>>> for val in foo():
...     pass
... 
Foo called
Still in foo

注意消息Foo called是如何在生成器上调用.next()后才打印出来的。在

您只调用递归函数,但它返回一个生成器,然后将其丢弃。代码本身永远不会执行,因为它被保留。而是在结果上循环:

^{pr2}$

现在实际迭代嵌套的生成器函数结果,并将其传递给调用方(外部嵌套生成器函数的使用者)。在

我假设这与你实际上没有递归地使用函数的输出有关。很难说你想用它做什么,但你可能想用它做些什么。e、 g.:

 for res in  extractIngredientInfo(...,...):
     yield res

而不是仅仅:

^{pr2}$

你必须注意如何使用recursion in a generator function。你必须小心你的生成函数会产生什么结果。在

def gen_f(n):
    for i in xrange(n):
        yield "hello"

def recursive_f(n):
    yield "hello"
    if n>0: for line in recursive_f(n-1): yield line
    # the above line is the tricky one, you might be tempted to
    # yield recursive_f(n-1) # but it won't work.

两者都是等价的,你可以称之为:

^{pr2}$

相关问题 更多 >