Tuesday, October 8, 2013

Recursion (Python)

Recursion means that the code will somehow call itself, usually for some smaller scale of the program. The recursive code will run until it hit the base condition and then it will trace back to the original call. The advantage of  recursion is that it can solve a complex problem with just a few code. There are two ways to visualize a recursion program:

The high-level view

This way of thinking is recommended, because is easier to adapt this thinking without losing your mind, useless you think like a machine. First, you have to convince yourself that the function works with the base case. Then focus yourself on doing a level 1 recursive trusting that the base case would work, then solves the next level without keeping in mind all the detail of level 1 implementation. Then ask yourself, in general if I can assume than n-1 case works, then you can solve n level problem,. If not, declare more base classes or change the recursive part of the code.  

Machine-level operational view

This way of thinking, you have to trace back the whole recursion, level by level. For Example:
_____________________________________________________________________

def koch_0(t, size): 
    t.forward(size) 
def koch_1(t, size): 
    for angle in [60, -120, 60, 0]:
         koch_0(t, size/3) t.left(angle) 
def koch_2(t, size):
     for angle in [60, -120, 60, 0]:
         koch_1(t, size/3) t.left(angle) 
def koch_3(t, size): 
    for angle in [60, -120, 60, 0]: 
        koch_2(t, size/3) t.left(angle)
________________________________________________________________________

This is the case, each call it traces back to the previous level of the call, until it hit the base case. 

Common mistakes

  1. Forgetting to return the recursive call. If there is no return from the call, it will not return the base case back to the call eventought it had the result that base call. 
  2. Forgetting to set a stop conditional to the recursive call. It causes the program to run until there are no more space in the memory to call the recursive function. 
  3. If you are assigning the result to a variable, remember to pass the variable on the call too. Because each time the recursive function calls, it will reset the variable. 

No comments:

Post a Comment