我使用Euclidean algorithm使用递归找到两个数字的最大公约数。
我感到困惑,因为在某些时候b的值将等于0,此时我已经指定程序返回a的值,此时此值应该是最大的公约数。
该计划不会这样做。相反,有人告诉我,我需要在其他步骤中的gcdRecur之前进行返回。但是为什么这是必要的,因为一旦b == 0,程序应该退出if语句?
def gcdRecur(a, b):
if b == 0:
return a
else:
gcdRecur(b, a%b)
gcdRecur(60,100)
答案 0 :(得分:3)
您需要实际返回递归调用的值:
return gcdRecur(b, a%b)
def gcdRecur(a, b):
if b == 0:
return a
else:
return gcdRecur(b, a%b)
答案 1 :(得分:1)
您忽略了递归调用的返回值:
else:
gcdRecur(b, a%b)
在那里添加return
:
else:
return gcdRecur(b, a%b)
递归调用返回值不会自动传递;它就像任何其他函数调用一样,如果你想要传回结果,你需要明确地这样做。
演示:
>>> 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