Thursday, 3 March 2016

Week 7 SLog

Recursion

Recursion is not something I look back at with fond memories. I'll try and summarize my understanding of recursion so far:

Recursion is when you create a function and you call on it within your return statement.
Recursion can be thought as jumping into oneself as deep as you can then working your way out.


Recursive Functions have 3 general parts:
The Base:
This is the simplest part of the function and requires no recursion at all. This is the point where you want your function to stop

The Work:
What is meant to be done at each step of the function

The Recursive Call:
Calling on the function within the function.

In class we went over this example:

def sum_list(L):
    if isinstance(L, list):
        return sum([sum_list(x) for x in L])
    else:
        return L


When this function is called it will try to go into the list as deep as it can then solve for that level and work its way out. ie
  >>> sum_list(17)
    17
    >>> sum_list([1, [2, 3, [4]], 5])
    15
Another great example is the fibonacci sequence. its like 5! is the same as 5*4*3*2*1.
Understanding recursion so far is pretty difficult but I'm sure by next week I'll be a pro.

No comments:

Post a Comment