递归函数的序列/堆栈图
对于下面的代码:
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]
序列图将如何变化,我想了解在执行此代码。
for the code below:
def printList(L):
if L:
print L[0]
printList(L[1:])
I can have sequence diagram like this:
# 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
So my question is if I change the code to:
def printList(L):
if L:
print L[0]
printList(L[1:])
print L[0]
How would the sequence diagram change, I want to understand what exactly happens during the execution of this code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
递归调用之后调用的打印语句将全部在“返回途中”被命中。也就是说,您的每个语句:“它到达函数末尾并返回 None”可以更改为“它打印 L[0] 的当前值,到达函数末尾并返回 None”,这将分别为3、2、1。
就像这样:
The print statement called after the recursive calls will all get hit "on the way back up". That is, each of your statements: "it reaches the end of the function and returns None" can be changed to "it prints the current value of L[0], reaches the end of the function, and returns None", which will be 3, 2, and 1 respectively.
Like so: