Friday 20 February 2015

Week 5 - Recursion

Recursion is used in order to repeat a similar task a (obviously) finite number of times. More specifically in code, this can be done by having a function to call itself. The thought is to divide up a problem into smaller parts and calculate those individually to finally get the answer as a whole.

For example, let's start with the most basic example of recursion I can think of:

def factorial(number):
    if number == 1:
        return 1
    return number*factorial(number-1)


Nothing complicated here, it was annoying enough to write it in this blog...Maybe next time I'll just put a screenshot of some code in an IDE. That would probably be easier.

The first part would be a base case for when the recursive function will simply return a result without going through any more iterations involving recursion. But before reaching the base case the function would call on itself in order to execute more steps recursively.

I had previously already encountered and learned about recursion so it was not difficult for me to understand it. Different syntax but not much change. I recall when I had first learned about recursion it would definitely help if I would actually write down each step on a piece of paper and go through the results backwards to see how the code works. Now I don't really have to do that with the rather simple examples we learned in class but it still is a good thing to learn. (The exercise/worksheet we did in class was pretty close to what I described but starting with multiple simpler examples instead of going through a more difficult one at the start) All in all recursion is a great concept and tool to learn and even though I know it can be incredibly difficult for some people to grasp at the beginning, at least they can be assured that it will be of great benefit to learn.

No comments:

Post a Comment