What Is Recursion
Recursion is the process of defining a problem (or the solution) in terms of (a simpler version of) itself. A function is recursive if it calls itself. Anything solved with recursion can be solved withiteration (looping) instead. However, it is not always as practical nor efficient. Unlike an iterative solution that is long, complex and inelegant, a recursive solution is concise and elegant.
- if you're home, stop moving
- if not, take a step toward home
- find your way home
Parts of Recursion
All recursive algorithms have the following:
- base case (i.e., when to stop)
- work toward base case
- recursive call (i.e., call ourselves)
To work toward the base case we make the problem simpler. The recursive call, is where we use the same algorithm to solve a simpler version of the problem. The base case is the solution to the "simplest" possible problem (e.g. the base case to adding a list of numbers would be if the list had only one number.Thus the answer is the number).
Why Recursion Works
In a recursive algorithm, the computer retains every previous state of the problem. This information is held by the computer on the "activation stack". Every function has its own workspace per call of the function.Reflection and Personal Thoughts
To me, the easiest part of recursion is tracing a recursive function that's already been written. In most cases, writing a base case is quite easy because you just have to think of the simplest case or when you want the algorithm to end. The trickiest part for me has been writing the actually recursive call. You know what the call will eventually return since you have the base case(s). Still, I believe I should practice more recursion exercises.Example of Recursion
Sum of numbers in a list:
def sum_list(L):
if not isinstance(L,list):
return L
else:
return sum([sum_list(x) for x in L])
No comments:
Post a Comment