Tuesday, February 24, 2015

Recusion

    Recursion has a somewhat tricky logic: A sublist inside a list that has the same format as its superlist. Yet recursions are always of the same format, for example, a sum recursion is as followed:

def sum_list(x):
    if isinstance(L, list):
        return sum([sum_list(x) for x in L])
    
    else:
        return L

    So it seems like the first thing to do is to check whether input L is an instance of list, that is, to check in the children node (which don't have subordinate level nodes) and see if it follows the basic conditions that we want, and in this case, L is checked to be a list or non-list: if its a list, there is a need to sum up the numbers within it; if not, the value L should be returned.
    Then go inside the list, using recursion and sum up the elements of children, and using the sum_list method itself to repeat the steps with its superclass and so forth. In the process, values from each subordinate level children are gathered into a list, from the very bottom level. The sum function sum up those values, but because sum function calls the list of values using sum_list(x), which is the function itself, the recursion occurs. For every element in list L, sum_list trace into the inner element of it through "for x in L", in a for loop way, and get a list of values in the inner list. The outer sum([...]) then sum up those values and return it to a superordinate level. The process repeats and we get the results.
    Once the process is understood, a recursive problem is not too hard.

No comments:

Post a Comment