Saturday, 1 March 2014

SLOG #5: Recursion

This week is quite special. Firstly we had quite a hard lab. I didn't get the idea of it until now. Secondly we had a midterm term during lecture time on Wednesday so we didn't actually learn a lot this week. Thirdly the topic of this week's slog is assigned to be recursion. Since I have posted recursion a little bit in the past few weeks, this week's slog is kind of like a summary.

Recursion is the process of repeating items in a self-similar way according to definition from Wikipedia. Basically in python, it means keeping calling the function itself in its function body until it reaches the base case. So we definitely can't leave out the base case or it would keep calling itself without stopping which causes a runtime recursion depth error.

Though we know recursion is convenient. We could make our code much shorter and clearer to read compared to iteration sometimes. It's not always easy to write a recursion. Through these weeks of exercise, I think figuring out the base case and next-most complex case firstly will be helpful. We could plug some simple cases to test our code. For example, for assignment 1(Tower of Hanoi), we first figured out how 3 stacks work. We started from moving one cheese (base case) without needing to using recursion. Then we started to think about 2-cheese and 3-cheese case and get the idea we could move all but the bottom cheese to the intermediate stool, bottom cheese to the destination stool, and all but the bottom from intermediate to destination. The concept of moving 2 cheeses to their destinations could be generalized to n cheeses. This is how recursion works. Keeping calling itself until it reaches the base case: the number of cheese is 1.

As posted in SLOG 2, compared to iteration, recursion has drawbacks such that storing certain values on the stack for each function call which takes time and space. Since until now we didn't encounter really complex context, the advantage of recursion is very obvious. We could consider using recursion any time we need to repeat objects or functions in a similar way.

Finally, feel free to leave comments here.

No comments:

Post a Comment