Thursday, 26 February 2015

week 7

Recently in class we've been focusing a lot of time on recursion. What it is, where it is found, and what uses it can serve. The first thing that stuck out to me with the concept of recursion was how it tackles a problem that is very unique, but also common in computer science.

Recursion is essentially a way of repeatedly accomplishing a task until the task at hand is solved or becomes the most simplified form that it can be. The term for this simplified form is the base case. The process which a recursive function works is that it looks at a given state of a task, runs itself to check to see whether or not the current state is the base case; if not, the process will perform a function to simplify the task by 1 step, and then calling on the function again to repeat the same process on the task in its new state. This will continue to loop infinitely until the task becomes it's base case, in which it is solved.

An example of this can be seen by this function in python that looks at every element of a list, and adds them together.

def listsum(numList):
   if len(numList) == 1:
        return numList[0]
   else:
        return numList[0] + listsum(numList[1:])

the important things to note to understand the process of recursion are the names of the function itself and it's input to run, the base case conditions, and the non-base case task.
This example takes an input of a list. This list can vary in complexity from being of length 1, to any other length. It's base case is when the list only contains 1 item in the list. If the list isn't 1 item in length, it will look at the first number in the list, and add to it the return value of the same function, on a list that has taken out the first value.
The function first examines the list and has an if statement to see if it is the basecase. if it isn't, the function takes the first number in the list and adds it with listsum(numList[1:]). So the function repeats itself until the basecase condition is met, and the sum of the entire list is returned.

. A nice part about recursion is that if designed correctly, it doesn't matter how complex the situation or problem is. It repeatedly examines the input and only compares it to see if it is equivalent to the base case, so it doesn't look at a problem a set amount of times.What makes this so useful is because it significantly reduces the amount of code that is needed to look at specific problems. It simplifies solutions while also making them more intricate and optimized

No comments:

Post a Comment