Week 5
Tracing recursion
Recursion seemed like a
very abstract topic at first. However, tracing code helps a lot when trying to
understand how it works. I would like to use a few lines to wrap my head around
this topic.
There is a few
techniques and concepts that our professors have been reinforcing on us. Among
them:
· It is important to realize that analyzing a few base cases can give us a good understanding of the whole picture. Don´t forget especial cases such as the empty list.
· When tracing, we don’t have to trace every single iteration. We can use the behaviour that previous cases had.
· We may not know how to implement recursive code right away, but we can make an educated guess, trace the code and make corrections.
· Recursion is the process of calling a function within the same function.
Let’s use these
techniques and concepts in the following recursive code.
def count_elements(L):
if isinstance(L, list):
return sum[count_elements(x)
for x in L]
else:
return 1
Considering a few Cases:
[] à 0 # Base
case Empty list
[1] à sum([count_elements(1)])
à sum([1]) à 1 # Base case List of grade 0
[[1], [2]] à sum([count_elements([1]),
count_elements([2])]) à sum([1, 1]) à 2 # We did not traced count_elements([1])
again, since we already did it in the example above.
[[1, [2]], 3, [4]] à [count_elements([1,
[2]]), 1, elements([4])] à sum([sum([count_elements(1), count_elements[2]]),
1, 1]]) à sum([sum(1, 1), 1, 1]) à sum(2, 1, 1) à 4
From the second case ([[1],
[2]]) we can notice that the aim of our function is to count the number of
elements.
Let’s say we did not
know what to put in under the else statement. In that case we can still follow
the same structure as follows:
[[1], [2]] à sum([count_elements([1]),
count_elements([2])]) à sum([sum(count_elements(1)), sum(count_elements(2)])
We would like our
answer to be 2, so we infer that we need to return 1.
As we can see, tracing
code is definitely useful and it has a direct application when dealing with
recursive code.

I thought you wrote an insightful summary of recursive thinking; although you forgot to mention how bigger problems need to be broken down into smaller ones for recursive calls. Otherwise we would run into infinite recursion!
ReplyDelete