Friday, February 20, 2015

Impressions of tracing recursion


def depth(L):
    """
    this function returns the depth of the argument if it is a list, else 0
    """

    if isinstance(L, list):        return 1 + max([depth(x) for x in (L + [’ox’])])    else: # L is a non-list
        return 0 




    This week we traced some recursion code, the basic idea is to trace from the simplest example like when the argument return list's depth, you start with depth([]), then depth([1]), depth([ 1, 2 [ 3 ] ]), depth ([ 1, 2, 3 [ 4, 5 [ 6, 7 ] , 8] , 9 ]).  The point is for you to get the pattern of the code and what it returns, then we trace some complicated argument input, and from the previous examples, you will get the idea of how the code works.

    When you see depth([1]) returns 1,  you will know that depth([1 , 2 [ 3 ] ]) the [3] returns one then [1, 2] count as another one, so it returns 2, then you know [ 4, 5 [ 6, 7 ] , 8]  in the 3rd example would return 2, and it goes on and on.  And that is how you trace a reclusive code.


No comments:

Post a Comment