Hello! In this SLOG, I'll be talking about recursion.
Firstly, what is recursion? In computer science, recursion
is when a function calls itself during its execution. The purpose of recursion is
to iterate over heavily nested lists. Recursion helps to reduce code complexity
since it can reuse itself to go deeper into a nested list. This is helpful when
the solution is to do the same thing in various depths of a list.
Before I talk more about recursion, I need to talk about
nested lists and about the depth of a list. The depth of a list is the maximum
number of lists within a list. We describe a non-nested list as having depth 1
and call it a flat list. So the list
[ [] ] is depth 2, while [ [[], []], [] ] is depth 3.
Recursion is a concept that is hard to imagine. I initially
thought that sum_list([]) would have resulted in an infinite loop. This could've
been avoided if I read the code without being primed to think about the
possibility of infinite loops. After being corrected, it became quite obvious
that recursion is just another tool and there is a general way to make it work.
You just need to have a clause for the general case to do recursion and a
clause for when you've reached the deepest part of a list or found what you
were looking for. Recursion could also be avoided by using an implementation of
loops.
The general form of recursion is:
if (condition to detect a base case):
(do something
without recursion)
else:
(do recursion)
Recursion is different from what I expected back in week 3. My
expectation was that we would just call the function in the body. The
implementation of recursion in class uses an if structure which allows us to avoid infinite loops. This is
because we will only do recursion if the base case is not met. In addition, we
usually iterate over the elements of the list for the general case so that it
will eventually reach the deepest level or fulfill the base case.
No comments:
Post a Comment