Sunday, 1 March 2015

Week 7

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 with
iteration (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.

For example, a function "to find your way home":
  1. if you're home, stop moving
  2. if not, take a step toward home
  3. find your way home
Solution to finding your way home: 1) we don't go home if we are already home; 2) we do a very simple action that makes our situation simpler to solve; 3) finally, we redo the entire algorithm.

Parts of Recursion

All recursive algorithms have the following:
  1. base case (i.e., when to stop)
  2. work toward base case
  3. 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