问题
This function in Python is to find the greatest common divisor of 2 integers recursively. But I was not able to get it to work as it should be in the test
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)))
回答1:
like my comment said. you are missing a return
in your else
statement.
else:
return gcdRecur(b%a,b)
You need the return statement here because you need to chain the return from your recursive. Using Sven Marnach
's function which can be found here: https://stackoverflow.com/a/5537507/4099813
We can take the trace function Sven wrote and see what's going on and why you need the return statement. (we need to modify his function to accept multiple arguments:
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)
Which when ran, it gives us :
|-- gcdRecur (45, 42)
| |-- gcdRecur (3, 45)
| | |-- return 3
| |-- return None
Notice it's returning None because you didn't state it should return the value it finds in the next level of recursion?
Adding the return
to the else
statement will yield:
|-- gcdRecur (45, 42)
| |-- gcdRecur (3, 45)
| | |-- return 3
| |-- return 3
来源:https://stackoverflow.com/questions/42277373/recursive-gcd-not-returning-expected-results