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.

No comments:

Post a Comment