英文:
Recursion on a function
问题
我正在练习Python中的递归。我在这段代码中遇到了问题,我以为它会打印53,但实际上它打印出了56。
def add(a):
if a > 30:
return 3
else:
return a + add(a + 3)
print(add(25))
起初,我以为函数只被调用一次。有可能当 a = 53
时,第一个 if 语句成立,所以它会添加另外的3吗?在这种情况下,答案就是 53 + 3 = 56
。然而,我不明白函数何时决定回到第一个 if
语句。
英文:
I am practicing the recursion in Python. Having trouble with this code, I thought it would print 53, but instead it gives me 56.
def add(a):
if a > 30:
return 3
else:
return a + add(a + 3)
print(add(25))
At the beginning I thought that the function was being called just once. Is it possible that when a = 53
the first if statement comes true so it adds the other 3? In that case that would be the answer to 53 + 3 = 56
However, I don't see when the function decided to come back to the first if
statement.
答案1
得分: 1
你的堆栈看起来像:
fun(25)
25 + fun(28)
25 + 28 + fun(31)
25 + 28 + 3
这解析为56。
英文:
Your stack looks like:
fun(25)
25 + fun(28)
25 + 28 + fun(31)
25 + 28 + 3
which resolves to 56
答案2
得分: 0
在第一次调用时,a
是25。因此调用 fun(a + 3)
。
在第二次调用时,a
是28。因此调用 fun(a + 3)
。
在第三次调用时,a
是31,所以返回3。
英文:
On the first call, a
is 25. Therefore fun(a + 3)
is called.
On the second call, a
is 28. Therefore fun(a + 3)
is called.
On the third call, a
is 31, so 3 is returned.
答案3
得分: 0
fun(31)
等于 3。
fun(28)
等于 28+fun(31)
,即等于 31。
fun(25)
等于 25+fun(28)
,即等于 56。
英文:
fun(31) is 3.
fun(28) is 28+fun(31), which is 31.
fun(25) is 25+fun(28), which is 56.
答案4
得分: 0
由于add
是一个纯函数,您可以使用等式推理来跟踪函数在每个步骤中的计算方式。
add(25) == 25 + add(28) # 25 > 30 为假
== 25 + 28 + add(31) # 28 > 30 为假
== 25 + 28 + 3 # 31 > 30 为真
== 53 + 3
== 56
英文:
Since add
is a pure function, you can use equational reasoning to trace how the function evaluates at each step.
add(25) == 25 + add(28) # 25 > 30 is false
== 25 + 28 + add(31) # 28 > 30 is false
== 25 + 28 + 3 # 31 > 30 is true
== 53 + 3
== 56
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论