Sunday, 1 March 2015

WEEK 7 - SUMMARY OF RECURSION- Topic to be graded

I chose this topics from the list of topics to be graded because this is a new topic which I am learning out of the listed topics so I have more to share on this topic than others. Recursion is calling a function within itself. For example to calculate a sum within a nested list the best way would be recursive calls of the function to the inner lists
def sum_list(L):
    """
    (int or arbitrarily nested list of int) -> int
    
    Return the sum of all ints in L.
    
    >>> sum_list([1, [2, 3], [4, 5, [6, 7], 8]])
    36
    """
    
    if isinstance(L, list):
        return sum([sum_list(x) for x in L])
    
    else:
        return L
A recursive solution is concise and elegant, an iterative solution is long, complex, and inelegant. For writing recursive code, thinking informally helped me a lot that is thinking if I had a bigger problem version of problem, then calling helpers on smaller versions of same problem and then using the result of helpers to solve the larger problem.
Recursion involves three steps
  1. Choosing a base case which would be our if statement
  2. Thinking of smaller instances of the same problem, tracing calls to smaller instances of the same problem
  3. Gathering the result from all the helpers (smaller instances) to solve the larger instant of the problem and return that in the else statement
Recursion was way easier following these steps. The part where I was usually stuck was second part. Thinking of smaller instants requiring recursion was a tough call. But practicing made me comfortable with second step. Most of the tree methods require recursive calls. It is easier for the node to ask it's children the required information than calculating itself. For example in the height function gathering height of all the children and finding the maximum out of them was better then using iterations for me. Recursion is making my coding life simple and easy.
The above code shows a same problem with recursion, for loop and while loop. The code for the recursion is shorter, simpler and elegant while in the case of loops it is longer and less elegant.
So overall recursive code made me understand the importance of beauty and elegancy in an programming language.

I would also like to share my recursive code exercises solutions from the lab here

No comments:

Post a Comment