Wednesday, 1 April 2015

Comments on Other Slogs

Here are the links for slogs I have commented on. My username is 'Jonah M.'

http://1001516978.blogspot.ca/2015/03/week-8.html?showComment=1427952547365#c4452472891915863170

# Commented on a Week 8 entry for Linked List

http://2015csc148slog.blogspot.ca/2015/03/week-10.html?showComment=1427952954087#c3872381094589234784

# Commented on a Week 10 entry for Binary Search Trees

http://dahai148.blogspot.ca/2015/03/week-7-recursion.html?showComment=1427953593832#c7185080502776559180

# Commented on a Week 7 entry for Recursion

Week 12: Efficiency and Final Comments

This week, we finished off a basic introduction to the principles of analysis regarding code efficiency. In particular, we learned how to classify the order of the runtime using 'big-O' notation. What this basically means is that no matter what size we are given, the runtime is proportional to some order based on the input size. We provide several examples to illustrate this point:

Ex 1) Single Loop

total = 0
for i in range(5000):
    total += 1
print(total)

Here the order is constant, denoted by O(I) since the code does not depend on any input values. Each time the code runs, it performs exactly 5002 operations (1 for line 1, 5000 for the for loop, and 1 for the print).

Ex 2) Two Loops

total = 0:
for i in range(n):
    for j in range(m):
        total += 1
print(total)

Here the order depends on both the sizes of two inputs, m and n, so the order is O(m*n). We know this because the nested for loop runs a total of n*m times. In the analysis of 'big-O' notation, we can disregard constants such as the first line and the print statement since O(m*n) can simply be multiplied by a constant to get the desired bound.

Ex 3) Branching Code

total = 0:
if (n % 2 == 0):
    for i in range(n**2)
        total += 1
else:
    for i in range(5, n + 3):
        total += 1
print(total)

Clearly, the order for the 'if' clause is O(n**2) and the order for the 'else' clause is O(n). In these cases, we take the worst case scenario as our official order since the worst case will always suffice as a bound for our analysis.

In sum, this basic analysis gives us a better understanding of how efficient our code is especially in cases where the input becomes arbitrarily large.

Final Comments: I am very satisfied with this course and feel I have learned a lot despite all the challenges. I hope to practice a lot before the final and showcase all that I have worked so hard to achieve. I look forward to taking further courses in computer science and expanding my horizons in this discipline.

Saturday, 28 March 2015

Week 11: Looking Back

This week, I will be revisiting my slog from week 7 which detailed the process of recursion. More importantly, I will be comparing my experience in learning recursion to that of my classmates in order to better understand where misunderstandings may arise.

We can take a simple example from the lab exercises:


 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)

One of my own misunderstandings when creating this code was the base case (which goes to show how even the simplest of things may present problems). I did not understand that when recursing through node.right or node.left, that the new node to be considered could ever refer to a NoneType so my base case had a different condition that node == None.

One my classmates, instead, had difficulty in returning a proper list. Since this function requires the recursion to return a list, each return statement, whether in the if or else clause, must return the desired values surrounded by square brackets (return [node.data] and not return node.data). This error caused my friends code to fail since the outputs were not even the same type. In addition, my friend also believed (wrongly) that:

[] + [3] = [[], 3] instead of [3] which obviously would have created problems in the code.

Perhaps even more important is the fact that we were able to fill in the gaps in each other's understanding of the recursive process so we were able to effectively learn from one another's mistakes.

As a final note, it is very important to understand that the construction of the base cases is intimately tied to the class implementation of the object that undergoes the recursion. For example, node.right and node.left have default None arguments which means that in recursion, the node will eventually equal None. For trees, on the other hand, there are empty lists so the object itself will never become None but rather []. As such, it is paramount to understand not just how to recurse but also how to modify the recursion according to the object type.

Overall, I am looking forward to the last week of classes learning about efficiency before exams!


Monday, 23 March 2015

Week 10: Assertion and Unittest

Having finished week 10 of the course, we learned how to make some basic unittests for our second assignment in addition to learning about the benefits (and potential drawbacks) of assertion statements. In particular, assertion statements are useful in being able to check if certain parts of the code (such as while loops) are doing what they were programmed to do. For example, given the following code,

if lnk.size > 0:
    prev_node = None
    cur_node = lnk.front

while cur_node and not cur_node.value == v2:
    prev_node = cur_node
    cur_node = cur_node.nxt

assert cur_node is None or cur_node.value == v2, 'Wrong Output'

Here, we perform a basic analysis of the conditions of the while loop. The program exists the while loop when its negation is fulfilled which occurs when either cur_node == None or cur_node.value == v2. By claiming assert with the following conditions we can see if our while loop indeed does what is programed to do for something that is not obvious by just looking at the code. The 'error string' after the comma is simply a message describing what the error is.

The advantages of using assert for complex while loops and other parts of code are numerous. First, it signals the presence of potential bugs/errors early on the code than if the entire program were allowed to run. This way, a programmer spends less time figuring out 'where' the code falters because there are more safety 'checkpoints'. On the other hand, just like commenting, an overuse of assert statements can be cumbersome and unseemly. In addition, too many assert statements could potentially slow down code since comparisons are being made in the assert statement itself.

One additional use of assert statements can be found in type contracts which serve to alert a programmer when incorrect input is given (which will inevitably flag potential bugs before the program is allowed to fully run). Here is an example:

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

Return a python list of all the values in the BST rooted at node that are between start and end (inclusive)
'''
assert isinstance(node, BTNode), 'node is not a BTNode: {}'.format(node)

Overall, I am looking forward to the last two weeks on analysing efficiency to make our code smarter and faster.




Friday, 13 March 2015

Week 9: Midterm and Preparing for Efficiency

Having just finished week 9, I am now entering the final stretch of the course, with just one more major assignment left and few new concepts to learn. Overall, the midterm was easier than I had anticipated and involved even a few questions that were more 'analytical' in nature such as finding the min height of a binary tree. If we define the height to be just the number of 'levels', so that a Tree with just a root has height 1, then for n nodes in a binary tree, the minimum height is the ceiling of log_2_(n) (where log is in base 2).

We make a simple observation to support this claim:

Level #                              Number of Nodes

1                                                 1 = 2^0
2                                                 2 = 2^1
3                                                 4 = 2^2
4                                                 8 = 2^3
...
n                                                 2^(n-1)

Since each node has a max of 2 children, the number of nodes in successive levels is doubled.


As such, for n = 20 nodes, we would have a minimum height of 5 since:

sum(levels 1 through 4) = 15 < 20 < 31 = sum(levels 1 through 5). As you can see, we take the ceiling of log_2_(n) since the remaining nodes will go into the next level giving the final height of the tree.

For me, this type of analysis was quite interesting and I am looking forward to learning about more intuitive and analytical ways to make my code more efficient by factoring in data structures, runtime, etc. As well, I feel that mathematics is best integrated into the more analytical side of computer science in making code more efficient by breaking down its components into digestible parts.

Overall, I am looking forward to the last 3 weeks and hope to finish off strong.

Saturday, 7 March 2015

Week 8: Linked Lists

This week during lectures we learned about a type of degenerate Tree called a LinkedList. In short,
each linked list has a front and back marker as well as a size which represents the number of nodes the list contains. Below is the code for both class LLNode and class LinkedList:

class LLNode:
    '''Node to be used in linked list
    nxt: LLNode -- next node
                   None iff we're at end of list
    value: object --- data for current node
    '''

    def __init__(self, value, nxt=None):
        ''' (LLNode, object, LLNode) -> NoneType

        Create LLNode (self) with data value and successor nxt.
        '''

        self.value, self.nxt = value, nxt

    def __str__(self):
        ''' (LLNode) -> str

        Return a user-friendly representation of this LLNode.

        >>> n = LLNode(5, LLNode(7))
        >>> print(n)
        5 -> 7 ->|
        '''

        if self.nxt is None:
            return '{} ->|'.format(str(self.value))
        else:
            return '{} -> {}'.format(str(self.value), str(self.nxt))

class LinkedList:
    '''Collection of LLNodes organized into a linked list.
    front: LLNode -- front of list
    back:  LLNode -- back of list'''

    def __init__(self):
        ''' (LinkedList) -> NoneType

        Create an empty linked list.
        '''

        self.front, self.back = None, None
        self.size = 0

For this week's lab handout, we were tasked with implementing several different functions that mutated Linked Lists, either updating values at particular nodes, inserting a node before another node, or deleting nodes all together. In traversing Linked Lists, it is important to understand that you cannot update backwards only forwards. So, if I 'overshoot' and find my node, I can't delete it or insert something behind it since I would have needed to do that in the previous node to the one desired. In these cases, two reference markers can be used, one for the current node and one for the node just prior. Below are some examples from the handout to illustrate the concepts better:

def insert_before(lnk, v1, v2):
    ''' (LinkedList, object) -> NoneType

    Insert a new node with value v1 before the first occurrence
    of a node with value v2.  Do nothing if no node has value
    v2.

    >>> lnk = LinkedList()
    >>> lnk.prepend(5)
    >>> insert_before(lnk, 4, 5)
    >>> print(lnk.front)
    4 -> 5 ->|
    >>> insert_before(lnk, 3, 5)
    >>> print(lnk.front)
    4 -> 3 -> 5 ->|
    >>> insert_before(lnk, 3, 7)
    >>> print(lnk)
    4 -> 3 -> 5 ->|
    '''
   
    if v2 not in lnk:
        return # We use the special method __contains__
   
    current = lnk.front
   
    if current.value == v2:
        lnk.prepend(v1) # Only for if v2 is the very first element in the LL
                                  # then there is no 'previous' node to reference

    else:
        while current.value != v2:
            pre = current
            current = current.nxt
        pre.nxt = LLNode(v1)
        pre.nxt.nxt = current

Here we have 3 cases. First, if v2 is not in lnk, then we just return without updating the list. This is easily checked using 'v2 in lnk' since we already have a special method __contains__ for class LinkedList. Secondly, we must separately check is the first node's value in lnk equals v2. In this case, we will prepend v1 (Note that in this case, the start of the list is already 'too late' so we need to use prepend). Thirdly, if the above two conditions fail, then v2 is somewhere in the middle of lnk. Here we initiate a while loop for current.value != v2 which sets our previous node to the current and our current node to the next node. That way, when the while loop is broken and current.value == v2, we assign LLNode(v1) to pre.nxt and then we assign the current to pre.nxt.nxt essentially reattaching the rest of the linked list to what we just inserted.

def delete_after(lnk, value):
    ''' (LinkedList, object) -> NoneType

    Insert a new node with value after the first occurrence of a
    node containing value, if possible.

    >>> lnk = LinkedList()
    >>> lnk.append(3)
    >>> lnk.append(5)
    >>> lnk.append(7)
    >>> lnk.append(9)
    >>> delete_after(lnk, 3)
    >>> print(lnk)
    3 -> 7 -> 9 ->|
    >>> delete_after(lnk, 7)
    >>> print(lnk)
    3 -> 7 ->|
    >>> delete_after(lnk, 15)
    >>> print(lnk)
    3 -> 7 ->|
    '''
    cur = lnk.front
   
    if value not in lnk:
        return # Ensures we won't have problems in the following while loop
   
    while cur.value != value:
        cur = cur.nxt
    cur.nxt = cur.nxt.nxt # We 'skip' over the node we want deleted

Similar to the function above, we have to check that if value not in lnk, we just return without modifying lnk. However, in this case we only have two cases not three since we are deleting AFTER a given node and not inserting BEFORE so we do not have a special case for the first node. In this while loop, once we have found that cur.value == value, we assign cur.nxt.nxt to cur.nxt. What this does is skip over cur.nxt and instead attaches this to cur.nxt.nxt which is the node just after the node we want removed.

    def __add__(self, other):
        ''' (LinkedList, LinkedList) -> LinkedList

        Concatenate LinkedList (self) to LinkedList (other) and
        return a new list, leaving self and other unchanged.

        >>> lnk1 = LinkedList()
        >>> lnk1.prepend(5)
        >>> lnk2 = LinkedList()
        >>> lnk2.prepend(7)
        >>> lnk3 = lnk1.__add__(lnk2)
        >>> print(lnk3.front)
        5 -> 7 ->|
        >>> print(lnk1.front)
        5 ->|
        >>> print(lnk2.front)
        7 ->|
        '''
       
        lst = LinkedList()
       
        current_node = self.front
        while current_node != None:
            lst.append(current_node.value)
            current_node = current_node.nxt
       
        current_node = other.front
        while current_node != None:
            lst.append(current_node.value)
            current_node = current_node.nxt
       
        return lst

Here, we have a more interesting case of concatenating two linked lists without modifying either one in the process. The code above traverses each list, appending each of its values to our new linked list until the current_node == None in which case our two sub-lists have been fully exhausted. I am curious to go to office hours and see if there is a 'cleaner' way of doing this function without having to traverse both lists independently. However, my previous attempts at concatenating the two lists using self.front, self.back, etc all resulted in at least one of the two sub-lists being modified which goes against the docstring.

Overall, linked lists have proved to be quite an ingenious and useful tool in the arsenal of computer scientists and I hope to study them more in preparation of Wednesday's second midterm.

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.

Saturday, 31 January 2015

Week 4: 'Re-re-re-re-...-cursion'

During the fourth week of lectures, we delved into the perennially dreaded topic of recursion (at least according to most people I know that have ever taken a computer science course). In essence, recursion works by defining something in terms of itself (this may occur multiple times until it is finally reduced to a base case for which a certain value is assigned). Recursion, then, can be distilled to two key elements: a base case for which the recursion 'ends' and an iterative case whereby the function passes a modified version of the argument through itself.

The most conspicuous examples of recursion occur in math, in both the Fibonacci sequence and the use of the factorial. In the case of the Fibonacci sequence, our 'base case' is simply the two numbers that start the sequence, which in this case are a_1 = 1 and a_2 = 1. From here, each successive number is derived by summing the previous two numbers in the sequence. As such, it is easy to see that if you wanted the 4th number in the sequence, you would sum a_1 and a_2 to get a_3 and then sum a_2 and a_3 to get a_4 (in this case, 1 + 1 = 2 = a_3 and 1 + 2 = 3 = a_4). With regards to the factorial, the following code explains recursion quite succinctly.

def factorial(n):
        if n == 0 or n == 1:
            return 1
        else:
            result = factorial(n-1) * n
            return result

As you can see, the base case occurs for n = 0, 1 which is defined to return 1 (since 0! = 1! = 1) and for all other cases, the function simply calls itself, but on a reduced argument (factorial(n-1) instead of factorial(n)) until n = 0 or n = 1 is reached, at which point the function terminates.

Although many students tend to find recursion a difficult concept to grasp, in reality, our brains are hard-wired to understand recursive thinking. For example, when you say someone is the 'great-great-great-great grandfather of person X', you are speaking recursively. The 'base case' occurs for the word 'grandfather' [0] which we all understand as 'the father of someone's father/mother'. Each successive addition of 'great' triggers a recursive call in which we simply apply 'father of' to our base case 'grandfather'. So, 'great-grandfather' [1] is the 'father of [0]'  and 'great-great-grandfather' [2] is the 'father of [1]', etc. So while we may find recursion difficult in a computer science sense, it really is a fundamental part of our everyday language that we rarely question or fail to understand.

As one last example of recursion in speech, we often define people/things in terms of other parameters. These parameters in turn, can be defined recursively as well in terms of other parameters. Although this type of recursion is not as clear as the example above, it serves to illustrate the point that our brains intuitively understand recursive thought. For example, take the following sentence:

'I went to see my mother today, whose car was parked next to a building, that had been recently bought by a millionaire, who owns three dogs.'

While it is a sentence few of us would ever be inclined to say, it's meaning is quite clear. The 'mother' is defined by the 'car next to a building' and the building, in turn, is defined by the face that it 'had been recently bought by a millionaire', and the millionaire, in turn, is defined by the fact that he/she 'owns three dogs'. So while this example is a tad convoluted at best, it elucidates the core principle of recursion as defining something in terms of something else.

Overall, this week's lessons in recursion were enjoyable as well as the lab which I found extremely helpful. Hopefully, recursion will become second nature by the time I am done with CSC148 since it is an extremely important and above all powerful tool in the arsenal of computer scientists.

PS: Hopefully the meaning of the title 'Re-re-re-re-...-cursion' is a bit more clear now.




Wednesday, 21 January 2015

Why Geeks Should Write

To be completely honest, one of the many 'perks' that pushed me into the direction of math and computer science was the fact that I would no longer have to 'write' (essays, reports, etc). However, I feel that 'writing' has been unduly monopolized in our everyday vernacular to represent a tedious, boring, and often fruitless task when it has the potential to be the complete opposite. Even for so-called 'geeks' who prefer to communicate using code, numbers, and more 'concrete' methods, writing is a process through which we break down, deconstruct, and analyze our thoughts. In so doing, we are not only distilling the crucial elements of new and often abstract ideas, but we are also making these concepts clearer to ourselves by connecting them with other ideas and experiences from our daily lives.

For example, in learning about vector spaces, the topics of 'linear independence' and 'spanning' were fundamental in understanding how to construct a basis for any vector space. At first, it was difficult to fully grasp the concept of a basis and how a finite number of vectors could represent an infinite number of items. Upon further reflection, the vectors of a basis seemed awfully similar to the blanks on any piece of identification. If we consider all humans as a vector space, each of us can be characterized by relatively few things--namely, our basis 'vectors' could be our age, height, nationality, gender, sexuality, income, location, etc. And in a broader sense, these few tidbits of information reveal a great deal about who we are, what our interests are, the people with whom we associate, etc. In addition, there is ample research that shows just how successful major companies are in marketing and advertising because they know the 'coefficients' of our particular basis 'vectors'.
By reflecting on what I had learned in class and connecting those fundamental ideas with structures in the 'real' world, I deepened not just my understanding of linear algebra but also my appreciation for it.

As such, I firmly believe that 'writing' in its most purest sense--reflection of concepts learned--can also greatly help 'geeks' to be able to both relate abstract concepts to the real world and to deepen their understanding of them. It is also important for 'geeks' to be able to relate their concepts to the real world since even the most abstract of ideas in computer science derive from problems in the real world (for example, data structures like stacks and queues and the principle of recursion are fundamental in computer science precisely because they are fundamental to how our own world works and functions). In conclusion, I challenge all self-proclaimed 'geeks' (myself included) to write and reflect about their experiences in their respective disciplines, not solely for the purpose of exercising the muscles of their hands but to exercise the muscles of their minds, in order to better connect the abstract with the practical and create the change and progress that we so desperately desire.