Thursday, 3 March 2016

Recursion


1. Recursion is an important programming technique that helps to write simple but powerful codes. Recursion means repeating the same jobs in a smaller scale until the pre-defined end (called base case) is reached. In this sense, a recursion is actually a loop. Recursive function is a function that continuously calls itself (called recursive call) to do the same jobs in the smaller and smaller range of the same data structure until the base case is reached. Hence such data structure is called recursive structure. For the recursive data structure, the most common base case is the empty state of the data structure like empty list ([ ]) and empty string (' '). Another common base case is "if the base case is/is not something" like "if the base case is not a list" and "if the base case is an even integer". Notice a recursive function may define multiple base cases.

2. A recursive function has a regular format:
   
        if base case is reached:
                do something
                return something (or return nothing)
        else:
               do something
               recursive call
               do something
               return something (or return nothing)
   
As mentioned above, a recursion is somewhat a loop because it has entry (1st recursive call) and exit (base case). But the recursion is not really ended when the base case is reached because it keeps coming back to the points of recursive calls until the point of 1st call is reached. So the recursive process can be divided into two sub-process: (1). coming down to the base case as a result of the recursive calls, and (2). coming back to the points of the recursive calls. Each recursive call is to repeat the same jobs in a smaller range of the same data structure. The results at the lower recursive calls can be returned to the upper recursive calls. So we get the final accumulated result when the highest recursive call (1st call) is reached. 
   
3. Now let's see the examples of recursion. 

a. recursively reverse a string like "abc" where the base case is the natural empty string (' ').
   
To reverse the string, we need to retrieve the characters one by one and then re-combine the characters.  At first, the recursion comes down to the natural base case: empty string ' ' as a result of recursive calls. The process is like:

1st call('abc') --> 2nd call'bc') --> 3rd call('c') --> 4th call(' ')

Next, we need to the lower recursive call to return character(s) in the smaller range of the string to the upper recursive call which combines with its 1st character of the smaller string. This process is like:

4th call(' '): return ' ' --> 3rd call('c'): return' ' + 'c' = 'c' --> 2nd call('bc'): return 'c' + 'b' = 'cb' --> 1st call('abc'): return 'cb' + 'a' = 'cba'   

So the recursive function is defined below:
      
 def reverse_str_recur(s):
                if len(s.strip())== 0:
                    return ''
                else:       
                    reversed = reverse_str_recur(s[1:]) + s[0]
                    return reversed

b. recursively count items of a nested list like [1,[2,3]] where the base case is "if the item is not a list".   

To count non-list items, we need to check if an item is a list or not. This is why the base case is defined as "if the item is not a list". As this is not a natural base case like empty string, the defined base case is applied to multiple items. At first, the base case is reached as a result of the recursive calls. The process is like:
   
1st call([1,[2,3]]) --> 2nd call(1) --> 3rd call([[2,3]]) --> 4th call(2) -> 5th call(3)

If the base case is reached, the non-list item is counted 1. With the List Comprehensions, we do not accumulate the results between the recursive calls but need a list to contain the results. This process is like:
   
5th call(3): return 1 --> 4th call(2):  return 1 --> 3rd call([2,3]): return sum([1,1]) = 2 --> 2nd call(1): return 1 --> 1st call([1,[2,3]]): return sum([1,2]) = 3

So the recursive function is defined below:
      
def count_items_recur(expr):
            if not isinstance(expr, list) :
                return 1
            else:       
                return sum([count_items_recur(i) for i in expr])

End of this post     

No comments:

Post a Comment