So I've written about recursion before, but now I think I understand it a lot better. After reviewing the recursive functions from class examples repeatedly, I can confidently break down what recursion actually means.
Recursion involves a function calling itself. However, there is always a base case, where there is no recursion involved. For example, take a look at the nested_depth function:
Here, the else clause is the base case. If L is an int, no recursion is involved, and 0 is returned. Recursion happens when there are lists, so if I have L = [1, 2, [3]], the function will go through the entire list before returning a value. Since L is a list, it will return 1. The first element of the list is 1, which is not a list, so it will return 0. Next, 2 is also not a list, so it returns 0. The next element is a list, which will add 1. for a total of 2. Now that the function has reached the end of the list, it will return 2.
Tracing through examples, starting with the base case, is very helpful because once I know the output of a simpler example, I can apply it to a more complicated example.

No comments:
Post a Comment