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.
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: