Friday, February 27, 2015

Week 7: Summary of Recursion

Before going to what I did this week, I want to go over the details on the recursion which I will be talking about. In my opinion, recursion is a brilliant way for one to be able to call the function inside the function to perform and apply the function to nested lists and its elements. Judging from what I had learnt so far, there are two types of recursion. One is a recursion involving  list or non-list. I will use the example from my week 5 SLOG entry to talk about this.

def length(L):
    """ (list or non-list) -> int

    Return the max length of the list (possibly nested list) in L.

    Pre-condition: L should be Python object either list or non-list.

    >>> length([1,2,3])
    3
    >>> length([1,[2,3,4]])
    3
    >>> length(12)
    0
    """
    if isinstance(L, list):
             return max([len(L)] + [length(x) for x in L])
    else:   # if L is not a list.
             return 0

Trace length([1,2,3,4])
--> max([len([1,2,3,4])] + [length(x) for x in [1,2,3,4]])  # since L is a list.
--> max([4] + [0, 0, 0, 0])
--> 4

Trace length([1,[2,3,4]])  # nested list recursion tracing example
--> max([len([1,[2,3,4]])] + [length(x) for x in [1,[2,3,4]]])  # since L is a list.
--> max([2] + [3])
--> 3

For this type of recursion, programmer has to consider the situation when L is non-list, thus how it will answer the function. The above, example, function length returns the max length of the list, usually, I have used both max, min and sum methods to create a recursive code. Of course, I also should not forget the case when L ,which is our parameter for function length, is a list. By implementing isinstance(L, list), computer immediately check if L is list type Python object. This method "isinstance( )" was one of methods which I have never encountered before, so it was really interesting for me to see how easily I can check whether something is list, int, float, or str.

When one talk about a recursion, you should not forget about tracing a recursion. As one of the examples provided, tracing a recursion shows a clear representation of how the recursive code will perform in various situations. Also when one is required to trace a recursion, a programmer needs to think about all the possibilities that might need to be consider. For function length example provided above, I need to consider the following cases:

- When L is non-list such as string, or integer.
- When L is a list but with no nested list
- When L is a list with nested list
- When L is an empty list
- When L is a list with nested list and nested nested list.

Usually, giving multiple tracing examples which have a different conditions enable for people to recreate a recursive code even without a docstring of the function.

Unlike a recursion involving a list or non-list, the second recursion involves the use of tree. For a tree, you can have a several leaves and internal nodes. This is actually what I have learnt during this weekend. I will use one of examples from this week's lab to explain the difference with the first recursion that I talked about. Please revisit lab 06 (Copyright goes to Danny Heap and Diane Horton) just in case how t which is a part of BTNode to understand the definition of t.left (node or leaf located on the left side of the root t) and t.right (node or leaf located on the right side of root t).

def height(t):
    ''' (BTNode) -> int

    Return the number of nodes in longest path in BTNode t.

    >>> tree = BTNode(23) #please refer to lab06 from CSC148 for any information. 
    >>> height(BTNode)
    1
    >>> 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)
    >>> height(b)
    3
    '''
    if t is None: # this means if there is no root, internal node and leaves. 
         return 0
    else:
         return 1 + max(height(t.left), height(t.right))

(Source: http://www.cdf.toronto.edu/~csc148h/winter/Labs/lab06/additional.py)


Unlike a recursion involving a list, when involving tree, you have just have to call the function without having to use "function(x) for x in L". At first, since I was only familiar with a recursion involving list or non-list, it was a little bit difficult for me to understand. However, with enough practices and help of T.A., I was able to get my code to work properly.

After reflecting on what I know and learn about a recursion, I begin to wonder if there is another type of recursion which is totally different from two recursions I talked about above. However, there is one certain thing that a recursion is also one of valuable basic programming lessons one have to take not just because it uses a lot in programming, but it also gives students a new insight on what computers are really capable of.

As for the summary of Object Oriented Programming, there is nothing new I learnt so far, so please refer to week 6 entry to find out what it is about.

I guess I already talked about most of things I have learnt this week. One thing I found easy about this week's lecture is the definition of leaves and internal nodes. Since I already memorized what these terms mean and how they work, it was really easy for me to follow a course materials. Now I will continue on my CSC148 assignment 2 which also involves a recursion.

I also commented on some of SLOGs that I felt it is good. Bottom links are some of SLOGs I had commented:

-http://chrisc148slog.blogspot.ca/2015/02/entry-3-recursion-recursion-recursion.html?showComment=1425095301984#c6525962159396058506
-http://sarcasticgradientdescent.blogspot.ca/

Just as a side note,  today I learnt about there is going to be a strike. I hope both parties, UofT and CUPE3902 unions can find a reasonable terms to avoid a long-term strike.

Thursday, February 12, 2015

Week 6: Object-Oriented Programming and Peek at Tree

This week, I learnt about Tree and recursion. Before going over what I did this week, I want to go over few things about object oriented programming.

So what is object oriented programming? Well, based on my knowledge object oriented programming also known as OOP is a code style in which takes a consideration of class, object, inheritance, and many more. This type of programming mainly focuses on object type which act as a data structure. For class, there are two classes which are parent and child. child usually takes what their parent code originally has and modify it. On my week 4 entry, I listed some example of class inheritance as well as how one can be able to use and implement the code of the parent code into child such as using name_parent.__init__(self, example1, example2). Very often object oriented programming also suggests what kind of function you can use on object type defined by the original creator.

My summary on object-oriented programming is that it may look difficult at a first glance, nevertheless, if you keep practice your code implementing both class and inheritance, you may be able to construct a code in which you do not need to type it over again, since the parent class code has the data that is required for the child class code. Since it is my second time learning object-oriented programming, I found very useful how I can just recall what was used from the parent class code and use it on other class.

One more thing I want to talk about is the use of the default in class inheritance. For instance, let's use an example below which is a typical example of class inheritance which I wrote out.

class ParentClass:
           """ Information omitted
           """
           def __init__(self, example1, example2):
                      """ Type Contract omitted, please refer to the week 3 and 4 entry for writing a
                      doc-string for init method.
                      """
                      self.example1 = example1
                      self.example2 = example2

          def add_it(t):
                      """ Type Contract omitted, please refer to the week 3 and 4 entry for writing a
                      doc-string for this function method.
                      """
                      raise NotImplementedError('Subclass needed')

class ChildClass(ParentClass):   #here, we can see that there is a subclass being used.
           """ Information omitted
           """
           def __init__(self, example1, example2, score=0):
                      """ Type Contract omitted, please refer to the week 3 and 4 entry for writing a
                      doc-string for init method.
                      """
                      ParentClass.__init__(self, example1, example2)

           def add_it(t):
                      """ Type Contract omitted, please refer to the week 3 and 4 entry for writing a
                      doc-string for this function method.
                      """
                      self.example1.append(t)     #assume that self.example1 is a list.


Here, judging from the above example, in ChildClass' __init__ method, there is score which says equal to 0. The use of '=' without using space indicate the use of default value. if the user does not type anything, then self.score automatically is assigned to a value 0. Although I learnt about this in CSC108, I often forget to implement the default method when needed, so just to remind myself again, I put it on this entry.

Now onto this week's materials. This week, I learnt about tree and recursion using tree. What is tree then? The best example of tree coding is Fibonacci tree branches example which helped me how tree actually  works in Python programming. Before going into tree coding, there were some terminologies that I had to be familiar of in order to understand this week's lab. Terminologies are as follows:

Terms to remember
Root: Beginning of the tree
Internal node: node with 1 or more leaves
Leaves: node with no child
Arity: maximum branching factor of  tree
Height: maximum depth of tree

Some terminologies were interesting such as leaves which has no child. At first, I had difficulty of learning these, but thanks to going over some problem during a lab, I was able to understand it completely without a problem. I will give some example using tree recursion on my next entry, so please get ready for it!

Just as a side note, I got my term test 1 and I did fairly well. So I am really happy right now. Starting next week, during a reading week, I am thinking of doing my upcoming assignment 2 for CSC148 class. Of course, I am also going to read as well, since it is a reading week.


                   



Friday, February 6, 2015

Week 5: Reviewing Recursion & unittest.TestCase

This week, I learnt about the unittest and testcase. Sadly, there was only one lecture this week due to the term test 1 taking a place. I didn't have any problem with unittest and how I need to use self.assertTrue( ), self.assertFalse( ), and self.assertEqual( ) method. Many things about unittest was already taught in CSC108 class, so I thought this week was a brief review week and preparation time for the term test 1. Personally, I thought the term test 1 went well, but I am certain that this does not mean I can slack off for the rest of the course. As this is only a beginning, I will do my best to review any new materials I am learning through this course.

Since I also did review recursion for my term test 1. I just want to go over it continuing from the last week's SLOG entry. Last week, I mainly talked about the simplest recursion example. This week, I want to go over the recursion example in the lab which I really had a trouble during the recursion lab. The example is as below.

def length(L):
    """ (list or non-list) -> int

    Return the max length of the list (possibly nested list) in L.

    Pre-condition: L should be Python object either list or non-list.
 
    >>> length([1,2,3])
    3
    >>> length([1,[2,3,4]])
    3
    >>> length(12)
    0
    """
    if isinstance(L, list):
             return max([len(L)] + [length(x) for x in L])
    else:   # if L is not a list.
             return 0

Trace length([1,2,3])
--> max([len([1,2,3])] + [length(x) for x in [1,2,3]])  # since L is a list.
--> max([3] + [0, 0, 0])
--> 3

Trace length([1, [2,3,4]])
--> max([len([1,[2,3,4]])] + [length(x) for x in [1,[2,3,4]]])  # since L is a list.
--> max([2] + [3])
--> max([2, 3])
--> 3

At first I was wondering how I can do the comparison of the length of two lists through recursion. Thankfully, TA told me to read the condition carefully which was given on the lab handout. Also instead of using list append method, I had to use + in order for me to create an instance where I can find the maximum length of the list among two lists given. Not only that, I was amused by how I can even find the maximum and minimum length of nested list in L.

What I thought difficult this week was use of stack and queue method in the lab. However, the most difficulty I had experienced was due to snow storm which made me totally exhausted. What I felt easy during this week's lecture was on the unittest, how I can import unittest and using unittest, I can use unittest.TestCase to evaluate at a certain given example whether the function within the class is working properly.

During this week's lab, sometimes lab material is hard to solve just by looking once. So I always think that it is best for one to look at the lab handout several times before the tutorial and actually try to solve the problem by yourself instead of asking TA that you just don't get it. I think just spending an hour for the preparation of the lab before the tutorial is really helpful and let you do well on the quiz.