Tuesday, 3 March 2015

Week5 - Tracing Recuesion

    Last week we learnt about recursion and how to trace a recursive function. I was fascinated when I first saw the recursive function example my professor showed:
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
    To understand recursion, we need to be able to know how it works. As the above illustrates, when the function runs, it will first check if L is the type of list; so the function will call itself to check the terms in the list. Therefore, after a few steps, L will be converted to the following:
sum(1, sum([2, 3]), sum([4, 5, sum([6, 7]), 8))
Therefore, the function will return the result "36".
    Tracing recursive function help me a lot on understanding the concept, it also teaches me how to analyze each step of the recursion. 

No comments:

Post a Comment