Thursday, March 3, 2016

SLOG Week 7

    This week, we continued working on recursion, a function calls itself one or more times in its body. Unlike last week, the concepts in this week are more complicated that we need to be more concentrated. When the professor introduced class Tree, I was struggling with the function leaf_count(t). I understood that node with no children is called a leaf, and the number of leaf would be one if there exists a root only in the Tree. However, I was wondering that if a root connected to an empty list, should we count that a leaf or not. Fortunately, the professor answered my question that the total number of leaf would remain one if the child is an empty list.
    The approach to write a recursive function body seems straightforward. The general form is divided into two parts. One is a base case without using recursion, and the other one is a general case that involves recursion. The following is an example: 

def leaf_count(t):
    """
    """
    if len(t.children) == 0:
           return 1
    else:
           return sum([leaf_count(c) for c in t.children])

Even though the step seems easy to understand, I still need more practice in order to get a good mark on the upcoming test.

No comments:

Post a Comment