Sunday, February 1, 2015

SLOG #2

    This week's main topic is recursion. Recursion means defining something in terms of itself. It is the idea that a computer program can break a problem into many smaller parts, then solve these smaller problems using the base case of the program. As we saw in lecture so far, recursion is very useful in solving problems that involve unevenly nested lists.
    At first, the concept of a function calling itself in its own function definition seemed very abstract and impractical to me, because it would seem that the function can get stuck on an infinite loop that keeps on calling itself, or it can simply raise an error because the definition doesn't make much sense. Then, as the instructor traced the code, I realized that the base case of each recursion method would serve to avoid an endless loop and at the same time split the problem into its simplest form. After some practice on tracing recursive codes, I felt somewhat confident in my understanding of recursion.
    However, the hard part about grasping the concept of recursion is producing a working recursive code that solves a problem, as presented during the laboratory activity. Specifically, the problem was to implement a function length(L) that returns 0 if the input is not a list, or the maximum length of any list in the input, including the input list itself. My first attempt at this problem went as far as figuring out the base case, when the input is not a list. That was quite easy because the problem explicitly stated that the function should return 0 if the input is not a list. I could not make any progress on the recursive part of the function for a long time, since I had no idea how to piece together code in a recursive manner that can determine the maximum length of lists within a list. I tried to mimic the example codes that I have traced during the same activity by calling the built-in function max() on a list comprehension that contains length(x). So the code looked something like return max([length(x) for x in L]). That did not work at all when I tried to trace an example call, since there was no way of determining the length of any list in the input, all it could do was return 0.
    After some more trial and error, it became clear to me that I needed to develop a sharper understanding of the problem, which motivated me to look at the goal again. As I read the line 'maximum of len(L) and the length of any of L's sub-lists, if L is a list', I suddenly had the idea of putting two max() functions into my function definition. Using that thought I jammed the code 'return max(len(L), max([length(x) for x in L]))' into my function definition and the doctest passed. It was probably just luck on my part, but from this experience I learned that writing a recursive function requires a clear understanding of a problem and also some planning before jumping right in.

No comments:

Post a Comment