变量值如何递归更改

我想知道整数变量如何在递归调用中更改其值。我有一个递归函数,在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)

运行代码后,最大值仍为-99999,没有任何更改,但是我得到以下打印结果

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

为什么在递归调用后maxnum返回其原始变量。 但是,如果我按如下方式创建类似数组的变量,则它可以工作

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
评论