Thursday, February 27, 2014

Reflecting on A1 and TT1: List Comprehensions and Recursion Conclusion

After A1, I thought I understood recursion very well. A1 really drilled the tracing technique for recursion into my head. I bet I traced the three stool method and four stool method millions of times! I even found a pattern to the optimal value of i, though it wasn't helpful for any coding. A1 was quite challenging not just because there were harder concepts to be coded, like recursion, but also because figuring out the details about TOAHModel and Tour was tricky. In essence, it was like “fill in the blanks” questions except with huge blanks to be filled in, which made it challenging. Yet, I got through it with proper implementations. However, now that I look back, I realized that I did not use list comprehensions. However, studying for term test 1 helped me practice coding with list comprehensions as well. Moreover, I also realized that I didn’t fully grasp recursion as I thought I did. For example: my first attempt to Winter 2013 test question # 4 was the following:
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.
"""
    count = 0
    for item in L:
        if isinstance(item, list):
            rec_len(item)
            count += 1
    return count

Of course, the above solution wouldn't work because the accumulator is overridden every time the function is recursively called. To use this accumulator idea, the variable would have to be a global one. This is where I finally figured the value of list comprehension. My final solution to the above problem was:
    return sum([rec_len(elem) if isinstance(elem,list) else 1 for elem in L])

This list comprehension is accumulating a list to be summed up in the end to find the total number of non-list items, fulfilling the need of an accumulator.

Now that I've practiced this idea and got through the test, I realize the list comprehension is a valuable tool for dealing with recursive functions.

No comments:

Post a Comment