Saturday, March 1, 2014

Recursion

We have been studying recursion for a couple of weeks. Recursion means defining something in terms of itself, perhaps multiple times to achieve an objective. In python, recursion means to solve the problem by calling the function itself to solve smaller problems. Recursion can simplify the code a lot when solving problems related to functions solving nested lists. During lectures, we saw examples for recursion which was tree_burst. At first I found tree_burst really hard to understand and follow as it was probably the first time I saw a recursive function. However, I found it really useful if you trace it for a couple of times.

Sometime during a lab we were requested to write recursive functions. I found it really confusing to write in the beginning, but my parented was very helpful, and we were able to finish the lab. Overall, recursion was not too bad for me as soon as I understood how to trace it, I think.

def rec_len(L):
    if isinstance(L, list):
        acc = 0
        for i in L:
            if isinstance(i, list):
                acc += rec_len(i)
            else:
                acc += 1
        return acc
The code above, for example, is a simple example of recursion that is used to counted the number of nested lists in a list. It recursively calls rec_len so that it will eventually goes through all of the nested lists in the given list L. 

No comments:

Post a Comment