Monday, March 3, 2014

Recursion

Recursion is essentially recalling the same method within the method.its a smart way to break down a problem into many small steps however with very little code.This is achieved by first identifying a base case (or multiple base cases) and solving smaller versions of the problem until this case is reached. 
here is the example of how to use recursion:
def nested_depth(L):
    """
    Return nested depth of list L.

    Nested depth is:
    0                                   --- if L is a non-list
    1 + maximum nested of elements of L --- if L is a list

    >>> nested_depth(3)
    0
    >>> nested_depth([1, 2, 3])
    1
    >>> nested_depth([1, [2, 3], 4])
    2
    """
    return (1 +max([nested_depth(x) for x in L] + [0]) if isinstance(L, list)  
       else 0)

Also ,i got it right in the midterm test.It is exactly same as above code.