gpt4 book ai didi

python - 递归函数的序列/堆栈图

转载 作者:太空宇宙 更新时间:2023-11-03 19:33:51 26 4
gpt4 key购买 nike

下面的代码:

def printList(L):

if L:

print L[0]

printList(L[1:])

我可以有这样的序列图:

# NON PYTHON PSEUDO CODE

PrintList([1,2,3])

prints [1,2,3][0] => 1

runs printList([1,2,3][1:]) => printList([2,3])

=> we're now in printList([2,3])

prints [2,3][0] => 2

runs printList([2,3][1:]) => printList([3])

=> we are now in printList([3])

prints [3][0] => 3

runs printList([3][1:]) => printList([])

=> we are now in printList([])

"if L" is false for an empty list, so we return None

=> we are back in printList([3])

it reaches the end of the function and returns None

=> we are back in printList([2,3])

it reaches the end of the function and returns None

=> we are back in printList([1,2,3])

it reaches the end of the function and returns None

所以我的问题是我是否将代码更改为:

def printList(L):

if L:
print L[0]
printList(L[1:])
print L[0]

序列图会如何变化,我想了解这段代码执行期间到底发生了什么。

最佳答案

在递归调用之后调用的打印语句都将在“返回途中”被命中。也就是说,您的每个语句:“它到达函数末尾并返回 None”可以更改为“它打印 L[0] 的当前值,到达函数末尾并返回 None”,这将分别为 3、2、1。

像这样:

PrintList([1,2,3])
prints [1,2,3][0] => 1
runs printList([1,2,3][1:]) => printList([2,3])
=> we're now in printList([2,3])
prints [2,3][0] => 2
runs printList([2,3][1:]) => printList([3])
=> we are now in printList([3])
prints [3][0] => 3
runs printList([3][1:]) => printList([])
=> we are now in printList([])
"if L" is false for an empty list, so we return None
=> we are back in printList([3])
prints [3][0] => 3
it reaches the end of the function and returns None
=> we are back in printList([2,3])
prints [2,3][0] => 2
it reaches the end of the function and returns None
=> we are back in printList([1,2,3])
prints [1,2,3][0] => 1
it reaches the end of the function and returns None

关于python - 递归函数的序列/堆栈图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4501309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com