python递归(如果条件满足,为什么程序不退出一次?)

2024-09-27 21:32:42 发布

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

我使用Euclidean algorithm来寻找两个数的最大公约数,使用递归。在

我很困惑,因为在某个时刻b的值将等于0,此时我已经指定程序返回a的值,此时这个值应该是最大的公约数。在

程序不会这样做。相反,我被告知我需要在else步骤中将return放在gcdRecur之前。但是为什么这是必要的,因为一旦b==0,程序就应该退出if语句?在

def gcdRecur(a, b):
    if b == 0:
        return a
    else:
        gcdRecur(b, a%b)
gcdRecur(60,100)

Tags: 程序returnifdef步骤语句algorithmelse
2条回答

您需要实际返回递归调用的值:

return gcdRecur(b, a%b)


def gcdRecur(a, b):
    if b == 0:
        return a
    else:
        return gcdRecur(b, a%b)

您忽略了调用的递归值:

else:
    gcdRecur(b, a%b)

在此处添加return

^{pr2}$

递归调用返回值不是自动传递的;它就像任何其他函数调用一样,如果希望返回结果,则需要显式地传递。在

演示:

>>> def gcdRecur(a, b, _indent=''):
...     global level
...     print '{}entering gcdRecur({}, {})'.format(_indent, a, b)
...     if b == 0:
...         print '{}returning a as b is 0: {}'.format(_indent, a)
...         return a
...     else:
...         recursive_result = gcdRecur(b, a%b, _indent + ' ')
...         print '{}Recursive call returned, passing on {}'.format(_indent, recursive_result)
...         return recursive_result
... 
>>> gcdRecur(60,100)
entering gcdRecur(60, 100)
 entering gcdRecur(100, 60)
  entering gcdRecur(60, 40)
   entering gcdRecur(40, 20)
    entering gcdRecur(20, 0)
    returning a as b is 0: 20
   Recursive call returned, passing on 20
  Recursive call returned, passing on 20
 Recursive call returned, passing on 20
Recursive call returned, passing on 20
20

相关问题 更多 >

    热门问题