2014年2月28日星期五

Week 7

Recursion is not intrinsically better or worse than loops - each has advantages and disadvantages, and those even depend on the programming language (and implementation).
In functional programming language implementations, sometimes, for loop can be very expensive and recursion can be very cheap. In many, recursion is transformed into a simple jump, but changing the loop variable (which is mutable) sometimes requires some relatively heavy operations, especially on implementations which support multiple threads of execution. Mutation is expensive in some of these environments because of the interaction between the mutator and the garbage collector, if both might be running at the same time.


In the past test, this question can be solved by recursion or loop.
def rec_len(L):
    """(nested list) -> int
    Return the total number of non-list elements within nested list L.
    For example, rec_len([1, 'two', [[], [[3]]]]) == 3.
    """
    result = 0
    if isinstance(L,list):
        for item in L:
            result += rec_len(item)
        return result
    else:
        return 1

or 
def rec_len(L):
    """(nested list) -> int
    Return the total number of non-list elements within nested list L.
    For example, rec_len([1, 'two', [[], [[3]]]]) == 3.
    """
   return sum(rec_len(x) if isinstance(x,list) else 1 for x in L)

Recursion is more convince.

没有评论:

发表评论