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.