I wonder how integer variable changes its value in recursion calls. I have a recursion function finding the max of an array as the following in python3
def recurse(arr,maxnum,size):
#base case: when it reaches the end of an array
if size== len(arr):
return
maxnum= max(maxnum,arr[size])
print('current max in recursion',maxnum)
recurse(arr,maxnum,size+1)
arr = [5, 1, 6, 0, 3, 7, 4, 2]
maxnum = -99999
recurse(arr,maxnum,0)
print('max result',maxnum)
after run the code, the maxnum was still -99999 without any changes, but I got the following print result
current max in recursion 5
current max in recursion 5
current max in recursion 6
current max in recursion 6
current max in recursion 6
current max in recursion 7
current max in recursion 7
current max in recursion 7
max result -99999
why is it that maxnum gets back to its original variable after recursion calls. However, if I create a array-like variable as the following, it works
def recurse(arr,maxnum,size):
if size== len(arr):
return
maxList[0] = max(maxList[0],arr[size])
print('current max in recursion',maxList[0])
recurse(arr,maxList[0],size+1)
root = [5, 1, 6, 0, 3, 7, 4, 2]
maxnum=-9999
maxList = [-999]
recurse(root,maxList[0],0)
print('list',maxList[0])
current max in recursion 5
current max in recursion 5
current max in recursion 6
current max in recursion 6
current max in recursion 6
current max in recursion 7
current max in recursion 7
current max in recursion 7
list 7