不理解递归行是如何执行的



这是我的代码,它只返回5和7硬币中amount>=24的变化。但是有一件事我不明白,那就是正在执行的这行硬币的序列。我知道python逐行执行代码,所以前一行coins= change(amount-5)是递归调用的地方,如果我运行34的main函数,它将是,coins= change(29)。但是函数在去到lines coins.append(5)之前,在这里调用了自己。那么它实际上是如何将5添加到change(24)最终返回的列表中呢?它实际上是在执行lines coins.append(5)之前再次调用自己从34开始的29 ?

def change(amount):
assert amount>=24, "Only amount>=24 is allowed"
if amount == 24:
return [5, 5, 7, 7]
if amount == 25:
return [5, 5, 5, 5, 5]
if amount == 26:
return [5, 7, 7, 7]
if amount == 27:
return [5, 5, 5, 5, 7]
coins= change(amount-5)
coins.append(5)
return coins
print(change(34))

输出:[5,5,7,7,5,5]

函数的每一层都有自己独立的coins变量——在调用之间不共享。

change(34)  
call change(29)
call change(24)
return [5, 5, 7, 7]  
append 5 to that 
return [5, 5, 7, 7, 5]
append 5 to that
return [5, 5, 7, 7, 5, 5]

顺便说一下,缺少2328的基本情况。如果我执行change(33),我将得到一个断言错误。

下面是它的工作原理:

|34 passed in function
|34 is bigger than all the conditions
||_34-5 is passed in the function
|| |29 is bigger than all numbers
|| |_29-5 is passed in the function 
|| | |Condition matched - 24. 
|| | |[5,5,7,7] returned
||_ 5 is added to the list
|_ 5 is added to the list

所以由于递归,找到了层。.append()将元素添加到列表的末尾。

然后得到[5,5,7,7,5,5]

最新更新