Sunday, February 23, 2014

Week 7 - Recursion

Recursion is the application of calling a function inside itself to solve a set of similar problems. As an example:

    def non_list(L):
    '''(list) -> int
  
    Return number of items in list that are not lists
  
    >>>non_list([1,'a',[[3],[]]])
    3
    '''
    count = 0
    for i in L:
        if isinstance(i,list):
            count += non_list(i)
        else:
            count += 1
    return count
   
  

In this example we are iterating over items of a list. In the even the item found is another list, we are able to call the same function, non_list, on the new list. This process repeats for all nested instances of lists, only counting non-list items. The recursive application in this function is how we are able to call non_list from inside itself, to solve the same problem for the inner lists. It is very useful in solving a set of similar problems, however I have not learned any of the applications outside of that yet (if they exist). It seems like recursion is restricted in what it can and cannot do, as to call itself it seemingly must be a similar problem.

That being said we have definitely taken advantage of recursion in 148. It has been used our first assignment, to assess and analyze trees, as well as in our lab of linkedlists. It was extremely advantageous and reduced the time needed to solve problems like those, so I can definitely see why it was learned. Initially, and from reading slogs I can see others often agree, recursion was a bit difficult to wrap our heads around; we had never traced anything like a recursive function. But through course readings, lecture examples, and hands-on work in the labs and assignment, I feel that I am now much more adjusted to the concept, and can use it to my advantage in the future.

No comments:

Post a Comment