Friday, January 30, 2015

WEEK 4 SLOG

   In this week, I learn the concepts about recursion on nested lists, recursion with turtles.

   We start to use recursion to write functions like sum_list and depth. These functions are required to implement actions to add or calculate depth of list in nested lists. Usually we build the function using list comprehensions. It is not a difficult concept to understand and I really enjoy to learn and use when writing code. However, one thing frustrates me is that some function call itself in list recursion. I put the example function code below. The problem is that I cannot understand if L = [1, [2, 3], 4] ) , when it enters the if statement and return 1 + max([depth(x) for x in L]). During the loop (list comprehension) , when x is any number or list in L, it will call depth(x). When x = 1, it enters else statement and return 0. This is the big problem that I catch with. In my view,  the function will return 0. But the truth is that after recording depth(0) = 0, the function will continue to implement list comprehension. In order to figure out my puzzle, l ask my classmate and then understand . Since calling depth(1) is in the process, it will not return and exit. I think it is so helpful  and fast for me to ask classmates relating to problems of learning. They can give you detailed answers.

   Furthermore, I think l am not confident  about the material that l learn in this week, because l did take more practice(using them to write some functions). In the weekend, l plan to do some by writing the past midterm paper.

def depth(L):
    ''' (list or non-list) -> int

    Return 0 if L is a non-list, or 1 + maximum
    depth of elements of L, a possibly nested
    list of objects

    >>> depth(3)
    0
    >>> depth([])
    1
    >>> depth([1, 2, 3])
    1
    >>> depth([1, [2, 3], 4])
    2
    '''
    # find the bug!
    if isinstance(L, list):
        return 1 + max([depth(x) for x in L])
    else: # L is not a list

        return 0

No comments:

Post a Comment