Python中的这个函数是递归地找到2个整数的最大公约数。但我无法让它在测试中发挥作用
def gcdRecur(a, b):
if a > b:
(a,b) = (b,a)
if b%a == 0:
#print("b%a == 0")
print ("a is " + str(a))
return a
else:
gcdRecur(b%a,b)
print("gcdRecur(45, 42) " + "should be 3, and we got " + str(gcdRecur(45, 42)))
print("gcdRecur(6, 12) " + "should be 6, and we got " + str(gcdRecur(6, 12)))
print("gcdRecur(12, 16) " + "should be 4, and we got " + str(gcdRecur(12, 16)))
print("gcdRecur(17, 12) " + "should be 1, and we got " + str(gcdRecur(17,12)))
答案 0 :(得分:1)
return
声明中遗漏了else
。
else:
return gcdRecur(b%a,b)
这里需要return语句,因为你需要从递归中链接返回。使用Sven Marnach
的功能,可在此处找到:https://stackoverflow.com/a/5537507/4099813
我们可以使用Sven编写的跟踪功能,看看发生了什么以及为什么需要return语句。 (我们需要修改他的函数来接受多个参数:
def trace(f):
indent = 0
def g(*x):
nonlocal indent
print('| ' * indent + '|--', f.__name__, x)
indent += 1
value = f(*x)
print('| ' * indent + '|--', 'return', repr(value))
indent -= 1
return value
return g
def gcdRecur(a, b):
if a > b:
(a,b) = (b,a)
if b%a == 0:
return a
else:
gcdRecur(b%a,b)
gcdRecur = trace(gcdRecur)
gcdRecur(45,42)
当跑步时,它给了我们:
|-- gcdRecur (45, 42)
| |-- gcdRecur (3, 45)
| | |-- return 3
| |-- return None
注意它返回None,因为你没有声明它应该返回它在下一级递归中找到的值?
将return
添加到else
语句将产生:
|-- gcdRecur (45, 42)
| |-- gcdRecur (3, 45)
| | |-- return 3
| |-- return 3