I'm currently learning recursion and I've come across a website that provides solutions to certain problems. One of these problems is finding a value in an array and returning the index using recursion. The solution provided is below:
def searchRec2(A, k):
if A == []:
return -1
if A[0] == k:
return 0
recS = searchRec2(A[1:],k)
if recS == -1:
return -1
return recS + 1
What I don't understand from this code is when the code uses the variable recS to run each recursive call of the search, once it finds the corresponding value in the array would it not return 0, and that 0 would be stored in recS.
So when it does the last return statement of recS + 1, is it not just doing 0 + 1 which is 1? I don't understand how it gets a value other than 1. (The code works it gives the index of the element we are looking for in the array.)


A = [2,3,4,5]andk=2. Write down and keep track of the variables & you will see how they change at each recursion.if A == []withif not Awhich is more Python and also faster (than a more complex list comparison).