Thursday 27 February 2014

Hello all, and welcome to my post about recursion. Now for those of you who aren't in the know, recursion is simply put, the definition of something by itself. In other words, its to when something uses its own self to define itself. Now although that concept may seem pretty vague and strange, but when it is applied to programming, it leads to some of the most interesting and really effective code you'll be writing (at my current level of programming). When recursion is applied in programming, it basically means that a method or function can call itself during its own execution. Take that in for a minute and really absorb the insanity behind that. You can basically call a function on itself to get to the results you want in a more user friendly way. For example, lets say you want to count the number of occurrences of a number within a list, now that list also contains sub lists, and even those sub lists contain sub lists of sub lists. Now that's a lot of sub lists, you could run the function multiple times on each individual list of sub lists and then add it up, or using recursion, you can write yourself up a function that will not only do the counting of occurrences for you, but also do the count inside of each sub list as well. Now in that specific case, let's say you make your accumulator for the occurrences of n, now for each item within the list L, if item is the number you're looking for, we add to the accumulator and we leave happy, otherwise, if L is an instance of list, then what you do is you call the function or method you are defining on the item and add it to your accumulator, that way it will make its own accumulator, check each item within, if the item is n make its own count, if its item is a list it will go again even deeper. Now like this, you'll be able to go into how ever many lists and sub lists you want, of course you will also need to make sure the function returns the accumulator so that when its called recursively, it has a value to give to its superior's own accumulator. So that is the simple definition of recursion, as well as a simple example of when and how you would implement it. Recursion can also be found at various different levels, including the case of Trees in CS, a tree is a recursion in its own rights, each node branches to two other nodes, that branch till their own nodes, with the exception of the leafs. Writing a Tree, or to display a Tree in python would absolutely require recursion, that way you could check each nodes value, and their children's value until you can't go any lower, and then it would move on to the next node.

So that is the quick rant of the week, about the Inception like recursion, this is something that can be confusing at times but is really effective when you start thinking recursively. As always this is merely my definition and if it is at all wrong I apologize. Thank you for reading.

-Just a CS student

No comments:

Post a Comment