I have been having a look at some simple recursive functions to wrap my head around the concept. However one example has me a little confused.
The function below uses recursion to obtain the largest integer from a list:
A = [-4, 2, 4]
n = len(A)
def findMaxRec(A, n):
if (n == 1):
return A[0]
else:
return max(A[n - 1], findMaxRec(A, n - 1))
As n will eventually equal 1 why does the function not always return the first element in the list?
CodePudding user response:
In such cases it might be helpful to just write out what code will be executed. I've tried to do that with your function as pseudo-code, where n
is replaced with its value:
findMaxRec(A, 3):
if (3 == 1):
return A[0]
else:
return max(A[3 - 1],
findMaxRec(A, 2):
if (2 == 1):
return A[0]
else:
return max(A[2 - 1],
findMaxRec(A, 1):
if (1 == 1):
return A[0]
)
)
Effectively, this results in:
max(A[2], max(A[1], A[0]))
Where the inner call max(A[1], A[0])
= max(2, -4)
= 2
And the outer call max(A[2], ...)
= max(4, 2)
= 4