Sunday, 1 March 2015

week 7 summery of recursive

I found tracing recursion is kind of fun and relatively easier than previous knowledge. However, I found it quite confusing when I first time be introduced the concept of it. It is easy to start with single list and couple sublists. I have to understand the simplest list and two elements list, then I can continually figure out the rest of recursion. But this is just a general way to solving recursive cases. As numbers of sublists are increasing, it is difficult to trace it correctly. When I brought my question to lab, TA explained tracing recursion step by step and I got better clue of it. The function keeps calling it self until it reach to the end. Recursion is efficient and useful during our programming. I realize the only way to have better understanding is writing and solving more recursive cases. 

During A2, I have used recursion in every function. It could simplify function call for itself. For example, in binary search tree, we can apply recursive during our search so that searching recursively go through from left to right in order to find the specific value in shorter time.



def list_internal_between(node, start, end):
        ''' (BTNode, object, object) ->

        Return a Python list of the data from all internal nodes of
        the tree rooted at node that are between start and end,
        inclusive.

        >>> list_internal_between(None, 3, 13)
        []
        >>> b = BTNode(8)
        >>> b = insert(b, 4)
        >>> b = insert(b, 2)
        >>> b = insert(b, 6)
        >>> b = insert(b, 12)
        >>> b = insert(b, 14)
        >>> b = insert(b, 10)
        >>> L = list_internal_between(b, 3, 13)
        >>> L.sort()
        >>> L
        [4, 8, 12]
        '''
        if node is None:
            return []
        else:
            left_list = (list_internal_between(node.left, start, end) 
                         if node.data > start
                         else [])
            right_list = (list_internal_between(node.right, start, end) 
                          if node.data < end 
                          else [])
            node_list = ([node.data]
                         if (start <= node.data <= end and not is_leaf(node)) 
                         else [])
            return left_list + node_list + right_list

For this function call, recursive function check children of the tree from left side to right side in post order. When we do the recursion, firstly, we break down the question into small pieces, then put them together or use them later.
            

No comments:

Post a Comment