Sunday, 2 March 2014

Week 7: Recursion

Learning the technique of recursion has made up a hefty amount of CSC148 so far. Upon hearing what it was for the first time, a function that calls itself within its own code, I thought it seemed relatively simple and I did not see much strength in it as a technique for programming. Essentially, a recursive function defines itself in terms of itself, something that I've always thought was not allowed, and valueless. Yet after many, many examples in lecture and labs, I can now see both it's complexity and importance. Although I say "complex", code is actually simplified with the use of recursion by breaking it up into sub-problems and running it all within one function one time. The concept of recursion, however, is more complex to understand than I first realized.

At first, I thought recursion was basically a while loop. As in it would keep calling the function until it had completed a loop through. Just like a while loop, if not implemented correctly, a recursive function will run infinitely. However, when it is controlled to run by using a base case, recursion works very well. The base case is virtually the function's "way out" and prevents it from just being circular by returning something.

Recursion, from what I can tell, is never completely necessary. There are ways to program without using it, mostly through for and while loops, yet sometimes it seems natural to use a recursive function because it can break up a problem into smaller pieces. Basically, the solution to the problem using a recursive function is dependent on the solution to smaller sub-parts of that problem as it moves closer to the base case.


Recursion is a good way to write code because it is more compact and is able to run through a larger problem without very complex code. Recursion divides and conquers a problem and returns the solution to all of those parts together. I definitely can now see the importance of recursion and how powerful a technique it is in Python. 

No comments:

Post a Comment