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.