Saturday, 28 February 2015

Week 7: Recursion Summary

Having just finished the week coming back from the break,  I would definitely have to say that my understanding of recursion has been much improved. This week's lab really helped me to clarify concepts in recursing through both Binary Trees and Binary Search Trees. Below, I replicate several example to clarify and elucidate the finer points of the recursive process.

class BTNode:
    '''Binary Tree node.'''

    def __init__(self, data, left=None, right=None):
        ''' (BTNode, object, BTNode, BTNode) -> NoneType

        Create BTNode (self) with data and children left and right.
        '''

        self.data, self.left, self.right = data, left, right

    def __repr__(self):

        ''' (BTNode) -> str

        Represent BTNode (self) as a string that can be evaluated to
        produce an equivalent BTNode.

        >>> BTNode(1, BTNode(2), BTNode(3))
        BTNode(1, BTNode(2, None, None), BTNode(3, None, None))
        '''

        return 'BTNode({}, {}, {})'.format(repr(self.data), repr(self.left), repr(self.right))

Here is the starter code for BTNode class along with repr which itself is recursive since it calls repr on each of the individual parts of the initial Tree (data, left BTree, right BTree).

One of the first functions we had to implement using recursion was parenthesize which would place the correct brackets on an expression contained in a BT where the leaves were floats and all internal nodes were one of four operators. The code is reproduced below.

def parenthesize(b):
    ''' (BTNode) -> str

    Parenthesize the expression rooted at b, so that float data is not parenthesized,
    but each pair of expressions joined by an operator are parenthesized.

    Assume:  -- b is a binary tree
             -- interior nodes contain data in {'+', '-', '*', '/'}
             -- interior nodes always have two children
             -- leaves contain float data

    >>> b = BTNode(3.0)
    >>> print(parenthesize(b))
    3.0
    >>> b = BTNode('+', BTNode('*', BTNode(3.0), BTNode(4.0)), BTNode(7.0))
    >>> print(parenthesize(b))
    ((3.0*4.0)+7.0)
    '''

    if isinstance(b.data, float):
        return str(b.data)
    else:
        return '(' + parenthesize(b.left) + b.data + parenthesize(b.right) + ')'

After a good hour of fiddling around with the function, I finally obtained the correct answer. Despite how difficult recursion may seem, the process I actually quite simple and it is of paramount importance to understand base cases and what exactly needs to be recursed. In this function for example, the simplest case would be to encounter a tree with data float (which must be a leaf). In this case, I just want to return str(self.data) with no parenthesizes added. Now I am halfway there.

If, I do not encounter a tree with b.data is float, then I know I am at an internal node which has one of the four operators listed in the docstring. This operator will be surrounded first by parenthesizes and then by the respective integers on either side to make the desired string. Hence, in the else statement, I return '(' + parenthesize(b.left) + b.data + parenthesize(b.right) + ')'. Hence in a simple tree with root '*' and children 7.0 (b.left) and 9.0 (b.right), my function returns a string:

'(' + parenthesize(b.left) + '*' + parenthesize(b.right) + ')' ---> '(' + '7.0'+ '*' + 9.0' + ')' ---> '(7.0*9.0)'

as desired.

We can also take a more complicated example, courtesy of Friday's lab in the function               list_between(BST, start end) which gives us a list of all the numbers between start and end (inclusive) contained in the binary search tree. Here we have the added challenge of not 'overrecursing' since the tree is a Binary Search Tree and hence will make the search quicker.

We reproduce the code below and analyse the base cases:

def list_between(node, start, end):
    ''' (BTNode, object, object) -> list

    Return a Python list of all values in the binary search tree
    rooted at node that are between start and end (inclusive).

    >>> b = BTNode(8)
    >>> b = insert(b, 4)
    >>> b = insert(b, 2)
    >>> b = insert(b, 6)
    >>> b = insert(b, 12)
    >>> b = insert(b, 14)
    >>> b = insert(b, 10)
    >>> list_between(None, 0, 15)
    []
    >>> list_between(b, 2, 3)
    [2]
    >>> L = list_between(b, 3, 11)
    >>> L.sort()
    >>> L
    [4, 6, 8, 10]
    '''

    if node == None:
        return []

    else:
        if node.data < start:
            return list_between(node.right, start, end)

        elif node.data > end:
            return list_between(node.left, start, end)

        elif (start <= node.data <= end):
            return [node.data] + list_between(node.left, start, end) + list_between(node.right, start, end)


Here we have a more involved recursion but the essential elements are unchanged. Our base case begins for when the node == None (which will eventually happen once we hit the leaves in which case, node.right and node.left will both be None). Here we return an empty list []. This step is important because adding an empty list does not change the components of our overall list since  
[1, 3] + [] = [1,3].

Now, we are halfway done and turn our attention to the else statement. Since this is a BST, it makes since that we would have 3 subcases: one for when node.data < start, for when node.data > end, and for when node.data falls in between the start and end values (inclusive). If node.data < start, then we recurse through list_between but this time just on the right branch since the left branch will still be out less than start but the right branch could potentially have an element greater than start. Likewise, for node.data > end, we just recurse through the left branch which could have an element less than end.

Lastly, if self.data is itself in [start, end], then we return itself (but inside a list so we can perform the list addition i.e., return [node.data] not just node.data) and then we recurse on BOTH branches since either the right or the left branch may contain additional elements in the desired interval.

Overall, Friday's lab was probably one of the most helpful experiences I have had in really understanding recursion because no matter how 'daunting' the task may seem, recursion can always be broken down into its base cases and an else statement. As such, it is useful to think of recursion in the following steps:

(1) Construct your most simple base case that does not even require recursion. The answer obtained here will be your base case or 'if' statement. Be sure to factor in nodes that are None for Binary Trees since they have a different __init__() from regular Trees.

(2) Ask yourself what your function needs to do to propagate forward the recursive process. This usually involves calling the function but on a modified argument (in this case, we would call it on the left and right branches respectively). Depending on how the argument is set up (whether or not to return a sum or a list), we would need to factor this into the recursive statement.

(3) Test the recursion from your base case to a simple recursive case to see if the function is implemented correctly.

Overall, I feel much more comfortable with the recursive process and hope to continue to understand it better going forward.

Sunday, 15 February 2015

Week 6: Review of Object-Oriented Programming

Having reached the halfway mark of the course, it is a more than opportune time to review the major concepts of object-oriented programming. Object-oriented programming can be broadly defined as programming through the use of 'objects' containing both data and methods. Broadly speaking, these objects are instances of classes which contain methods through which each object (aka 'self') can be modified.

The major concepts we have learned thus far concern classes and inheritance, recursion, and abstract data types (ADT's). We briefly review each major concept:

(1) Classes & Inheritance

A class essentially is a blueprint for the creation of an object, which is itself an instance of the class. Below is the code for a parent class named Employee. We analyze its components.


class Employee():
    """
    An employee.
        eid: int        - This employee's ID number
        name: str       - This employee's name
        SIN: int        - This employee's social insurance number
        pay_period: str - This employee's pay period, either 'weekly' or
                          'monthly'
   
    This is an abstract class.  Only child classes should be instantiated.
    """
   
    def __init__(self, eid, name, SIN, pay_period):
        """
        (Employee, int, str, int, str) -> NoneType
        """
       
        self.eid = eid
        self.name = name
        self.SIN = SIN
        self.pay_period = pay_period
        self.pay_history = {}
       
    def amount_of_pay(self):
        """
        (Employee) -> float
       
        Return the amount that this Employee should be paid in the next
        pay period.
        """
       
        raise NotImplementedError('Implemented in a subclass')
       
    def record_pay(self, date):
        """
        (Employee, str) -> NoneType
       
        Record the amount this Employee should be paid for the next pay
        period in their pay history, with the associated date.
        """
       
        amount = self.amount_of_pay()
        self.pay_history[date] = amount
       
       
    def total_pay(self):
        """
        (Employee) -> float
       
        Return the total amount of pay this Employee has received.
        """
       
        return sum([amount for (day, amount) in self.pay_history.items()])

The parent class serves to encapsulate the salient properities that are common to ALL subclasses. As such, record_pay and total_pay are implemented in the parent class using of course arguments obtained from the child class (as seen in amount_of_pay). In addition, the __init__ contains each employee's SID, name, and eid since ALL employess are characterized by these features regardless of their subclassification. As a final point, methods that the parent class cannot complete contain a 'raise NotImplementedError' to signify that these methods are to be executed in the subclass.
   
(2) Recursion

Recursion is the esentially the use of repeated sub-problems to solve one larger problem. In other words, recursive methods or functions call upon themselves a certain number of times, 'reducing' the overall problem to a 'base case' for which an assigned value can be given. This is why most recursive functions have an if and else statement where the 'if' serves as the base case scenario and the 'else' is responsible for propelling the recursive process forward until the base case is acheived. We demonstrate this process with the following code:

def length(L):
    '''
    (list or non-list) -> int
   
    Return 0 if L is not a list, or the maximum of len(L)
    and the lengths of L's non-empty sublists.
   
    Assume: L is a non-list, or a non-empty list
   
    >>> length(17)
    0
    >>> length([1, [2, 3, 4, 5], 6])
    4
    >>> length([1, [2, 3, [4, 5]], 6])
    3
    '''
   
    if isinstance(L, list):
        a = max([(length(x)) for x in L])
        return max(len(L), a)
    else:
        return 0

Here we have two cases. If L is not a list, we assign 0 (our base case). If L is a list, then we must return the max length of the sub-lists in L (including L itself). So if L is a list of 3 elements, and one of those elements is a list of 4, we would return 4 (not 3). Similarly, if L is a list of 10 integers, we would return 10 since no inner elements are themselves lists (and hence would be assigned 0 by the base case). Analysing the 'if' clause, we can see a few things: Firstly, if L is a list, the clause executes and we create a variable a which gives the max([length(x) for x in L]). So, for each element x in L, length(x) is called, executing the recursion. This value is then compared with the length of L itself to determine if either L is the longest list or if there exists a nested list inside L which is longer.


(3) ADT's (stacks, queues, trees)

Stacks and queues are data structures that essentially work in inverse manners. A stack contains a list of items or objects in which each new item to be 'pushed' (or added) is placed on top of the previous ones. As such, it is a 'last in first out' system since the last item on top will be the first to be 'popped' or removed. Queues function in the opposite manner so that the first item in is the first item out ('first in, first out'). Adding to a queue (or enqueue) adds to the end of the list while dequeuing (removing from a queue) takes away the first item in the list.

The last item to discuss is trees. Trees are characetrized by nodes which contain 'data' that the user needs. Except for the root or first node, all other nodes have a single parent node and possibly several children nodes (unless the node is a leaf in which case it is the final 'level' in the tree). We provide one example of recursion in a Tree class to conclude. Here is the code for finding the height (or number of levels of nodes in a tree):

def height(t):
    ''' (Tree) -> int
   
    Return height of Tree t,
    >>> tn2 = Tree(2, [Tree(4), Tree(4.5), Tree(5), Tree(5.75)])
    >>> tn3 = Tree(3, [Tree(6), Tree(7)])
    >>> tn1 = Tree(1, [tn2, tn3])
    >>> height(tn1)
    3
    '''
    if t.children:
        return max([height(c) for c in t.children]) + 1
    else:
        return 1

This code asks each successive group of children nodes for their height and passes this information on, accumulating +1 for each level until the root node is reached at which point the 'else' statement executes adding +1 to the final answer.

Overall, trees have proven to be an interesting and rather complex concept that I hope to work more with in order to better integrate my understanding of recursion and abstract data types in general.

Wednesday, 4 February 2015

Week 5: Tests and Testing

During Monday's lecture, we discussed the various aspects of testing such as constructing test cases and boundary conditions, while at the same time not 'over-testing'. Perhaps the most logical thing to compare testing to is a sieve. With testing, the objective is to 'catch' as many ways possible where you function could execute incorrectly or cause an error. As such, it is necessary to construct various 'gradations' or 'filters' each more refined than the last until all potential errors have been dealt with.

The challenge for me lies in the proper construction of test cases. At times, just starting an assignment, or even a problem in general, it is hard to envision where potential errors will arise in the code since functions, methods, and classes tend to all be interconnected and often make very different assumptions about what input will be and how it is to be handled. We can analyze the example used Monday to illustrate this point. Observe the following function:

def insert_after(L, n1, n2):
    """
    (list, int, int) -> NoneType
   
    After each occurrence of n1 in L, insert n2.
   
    >>> L = [5, 1, 2, 1, 6]
    >>> insert_after(L, 1, 99)
    >>> L
    [5, 1, 99, 2, 1, 99, 6]
    """
   
    i = 0
    while i < len(L):
        if L[i] == n1:
            L.insert(i+1, n2)
            i += 1
        i += 1

While it seems simple enough (i.e., just placing n2 after each occurrence of n1 in a list L), it can in fact pose several hidden pitfalls. For example, what if n1 and n2 are equal?  If the last line of code     (i += 1) outside of the while loop were absent, an infinite loop would be triggered after the first occurrence of n1. Why? Because adding n2 after n1 and indexing up 1 means the next number to compare in the list is the newly-added n2 which equals n1 so the while loop would execute ad nauseam.

As such, while many peoples' first test cases would focus on the numbers themselves (i.e., negatives, 0) or on the composition of the list (i.e., no occurrences of n1, few occurrences of n1), the real pitfall lies in the relation between the two parameters n1 and n2 (a much less intuitive test case). After having studied this example more thoroughly, I more fully appreciate the importance of developing strong test cases BEFORE starting to code away. Not only will this make individual functions like the one above 'bulletproof' but it will also prevent a potentially devastating cascade of errors further down the road when this function (or others) could be incorporated into larger problems. After all, a chain is only strong as its weakest link and analogously, a module is only as strong as its weakest function.

On a final note, the term test went well and was less difficult than what I had expected. Although the first question took more time than I expected, it was definitely 'doable' in the 50 minute time-frame allotted. Overall, going into week 6, I am both happy that reading week is fast approaching and that I have made good progress so far in the course.