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

python recursion (why won't program exit once if condition is met?)

我正在使用 Euclidean algorithm 通过递归找到两个数的最大公约数。

我很困惑,因为在某个时候b的值会等于0,此时我已经指定程序returna的值,此时应该是最常见的除数。

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

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

您实际上需要 return 递归调用的值:

return gcdRecur(b, a%b)


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

您正在忽略 递归 调用的 return 值:

else:
    gcdRecur(b, a%b)

在此处添加 return

else:
    return gcdRecur(b, a%b)

递归调用return值不会自动传递;它就像任何其他函数调用一样,如果您希望返回结果,您需要明确地这样做。

演示:

>>> 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