Saturday, March 1, 2014

#3 SLOG Recursion

Hi guys, today's post is going to be about one of OOP's amazing features, recursion.

Basically, recursive means the function calls itself recursively. Recursion can be successfully achieved is because that the function of each execution in the stack has its own shape parameters and local variables. So it can run by itself without the reference of other functions.

In the first few weeks, I was quite confused about the topic of recursion. As a beginner of Python, the concept and the essence of recursion give me a hard time grasping. After working on A1, I finally grasped the essentials that it really helps if you start thinking about the base case first. This simplest case sometimes is the key to the solution. After you have implemented the base case, think of the function as a more complicated version of the simple case and use it like you would a variable. But remember however complex the algorithm is, it will always result in the simple case. It just remind me of the simple induction learnt in the course CSC 165, in which we first solve the case where n=1 and then pass on to the n and n+1 cases to prove the whole problem. Despite the induction part, the idea is almost the same with the recursion - deal with base case first.

The recursion has the ability to call itself. At first I was like "how can something have itself inside it?" Now I know the 'itself' inside the function is actually the base case. Just like a tree, think the branch as the base case of it and a branch can have another branch on it which can have another branch on it, that is recursion.

For example if you want to find the sum of all numbers in a list that may also be a nested list. When we are still in the course of CSC108, we may think of utilizing for loop for 10 times or 30 times. But what about a million lists inside the variable list? What do you think would be the solution to this problem?


Undoubtedly the answer is recursion. Those a million lines' code can be written even in a single line. Magic, isn't it? That's why for computer scientists, recursion is very important as it enables us to solve problems quickly and efficiently. It might not be easy to think recursively at first but in the end it's still worth it. Try to break down the procedure and come up with the base case first, everything will be working out soon. Learning to use recursion can not only make your program more efficient, it will also help increase you own thinking skills.

1 comment:

  1. Recursion is not always preferred compare to loops. Because of the fact that it calls itself from inside, memories can not be released until the base situation is reached, which means the code would probably crash in your 1 million example...

    ReplyDelete