Thursday, April 2, 2015

Revisit an earlier SLOG posting of myself

Recursion has been a pretty important part of the course, with many different examples being given in class. In Assignment 2 and Assignment 3, we are required to use recursion to implement the functions. We spent lots of time discussing this topic in class. Thus, I prefer to revisit my earlier post on recursion so that l can review this important topic and strength the knowledge 

In my earlier post, l said that l had problems with understanding recursion. 
Here is the former code that l don't understand.

def depth(L):
    ''' (list or non-list) -> int

    Return 0 if L is a non-list, or 1 + maximum
    depth of elements of L, a possibly nested
    list of objects

    >>> depth(3)
    0
    >>> depth([])
    1
    >>> depth([1, 2, 3])
    1
    >>> depth([1, [2, 3], 4])
    2
    '''
    if isinstance(L, list):
        return 1 + max([depth(x) for x in L])
    else: # L is not a list
        return 0

Now, l think this is not difficult to understand this piece of code. But l still have problems with  recursion. One thing that I found definitely helped me understand this better was simply tracing very small test cases and writing by hand what happens at each step.
Recursive functions make the code look clean and elegant, but hard to understand. l find that there has some structures to write recursive function. it might help me to understand recursion function deeply.
  1. if xxxxxxx:
          return  xxxx     #it’s base case
      else:
          xxxxx    #  calling  the function
  The recursive function previously shown belongs to this kind of structure.

 2. 
     I would like to show this kind of structure by using the code l wrote from Assignment 3.
     It’s always one line.

  def node_count(root):
    ''' (GameStateNode) -> int
     
    Return the number of nodes in the tree rooted at root.

    >>> s = SubtractSquareState('p1', current_total = 6)
    >>> root = GameStateNode(s)
    >>> root.grow()
    >>> node_count(root)
    13
    '''
    return 1 + sum([node_count(x) for x in root.children])



Overall , I am really enjoying learning python, although it is hard for me to master the material. Practicing to write recursive functions is an important part in developing my skills in applying recursion effectively as well as  helping grow my knowledge base in python. Assignment 2 and 3 are good practices for me to grasp the content of recursion as well as the labs.  l find that he more you practice, the more you gain.

Many other SLOGs that I have read from other classmates seem to agree with the
idea that the more you practice the more you grasp the material. They think that the good way to understand the recursive function is trace very small test cases and write by hand what happens at each step, it's just the same like what l think.

Sunday, March 29, 2015

week 9 and 10 slog


Danny talked about binary search trees and sorting algorithms in terms of their time complexity in week 9 and 10. We missed our labs because of the strike, actually l was so annoying about it. We loosed the right to be tutored and learned knowledge.  We had test 2 on the week, it was not difficult . It just tested the material that Danny talked in class. And this week was the deadline to submit the assignment 2. The assignment 2 was very challenging, the most difficult part is to design the minmax_strategy class. I spent several days trying to come up with an idea for the minmax, which is a class that determines how the computer player play with the human player and which position is the best choice for the computer player to go, l really did not know how to implement it. But finally my partner finished the minmax class! Since l am not familiar with how to design a complete game program(I didn't  learn computer science in high school),  l think l should hire a tutor to teach me more about how to design a program in summer hoilday(like our assignment).

Saturday, March 7, 2015

Week 8 slog


The impression of this week
This week’s lectures focus on linked lists. And I find that I don't fully grasp the materials about linked lists presented in lectures.  Unfortunately, due to the CUPE 3902 strike, we no longer have tutorials to seek assistance. Based on CSC148's Information Sheet, I expect the term test 2 will occur next week, so we probably will be tested on linked lists. 


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

        Insert a new node with value at back of lnk.

        >>> lnk = LinkedList()
        >>> lnk.append(5)
        >>> lnk.size
        1
        >>> print(lnk.front)
        5 ->|
             '''
        new_node = LLNode(value)
        if lnk.back:
            lnk.back.nxt = new_node
            lnk.back = new_node
        else:
            lnk.back = lnk.front = new_node
        lnk.size += 1

As shown above the method in link list,  my doubt is that after assigning new_node
to lnk.back.nxt, why not set lnk. back = lnk.front? After checking lnk.front and lnk. back , I find they are same at this step.


My plan 
  My plan is to review some lecture notes before the exam and to re-do the labs. My destination is to catch up on the whole materials we learned these weeks.  I will complete the lab exercise 7 later today. l will go to the office hour to figure out my problems relating to link lists.

Saturday, February 28, 2015

Week 7 slog

      In this week, we continue to study tree, but not exactly the same material of the last week. It’s binary tree, a bit different from tree. We also learn how to implement recursive methods on binary tree. Danny talked about evaluate method and bst_contains method in class. Those are recursive methods, recursion codes can be helpful to eliminate the length of the codes we write and increase the correctness. These basic recursive methods implemented on trees are not very hard to understand in lecture, but this week’s lab is very tricky. I wrote the codes too long and cannot detest the error when i wrote it, the codes wouldn’t run because of it. lt might be that l didn't fully grasp the material of recursion and binary trees. I asked the TA for help frequently during the lab section and found the methods that asked us to implement were really difficult to write correctly, most of time they cannot run. But the quiz was easy for me.The TA was really nice, before the quiz he told us some answers of the lab exercise about the lab,  he talked about list_longest_path() method which frustrated me quite al lot, this method is related about the recursion but much harder to figure out. With TA’s help, l was still lack of  one method to fill out,  l think l must spend extra time on the lab exercise and check my work this week.

Thursday, February 26, 2015

Object-oriented programming (OOP)







Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs.Object Oriented Programming involves the creation of objects which contain both data and functionality together. It involves defining your own class and creating attributes (properties created for the object) and methods, which are operations that can be performed for an object. Everything in Python is an object. The user defined objects are created using the class keyword. From classes we construct instances. An instance is a specific object created from a particular class. Consider this pieces of code (retrieved from the CSC148 course website):

from math import sqrt

class Point:
    """
    A n-dimensional point.
    coords is a list of numbers containing the coordinates
    of this Point.
    """

Attributes

Attributes are characteristics of an object. A special method called __init__() is used to initialize the attributes of an object.

def __init__(self, coords):
        """
        (Point, list of number) -> NoneType
        
        Initialize this point with these coords.
        We will return to this docstring to add an example
        showing that p is as it should be.
        
        >>> p = Point([3, 4.0, 5.32, 6, 7])
        >>> p.coords
        [3, 4.0, 5.32, 6, 7]
        """
    
        self.coords = coords
    
In this code example, we have a Point class. The special method __init__() is called automatically right after the object has been created.

Here we pass an attribute to an instance object.

p = Point([3, 4.0, 5.32, 6, 7])



Methods

Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. For example, we might have a distance_from_origin() method in our Point class. The distance_from_origin() method returns the the distance from the particular Point to the origin.

def distance_from_origin(self):
        """
        (Point) -> float
    
        Return the distance from this Point to the
        origin.
        
        >>> p = Point([3, 4])
        >>> p.distance_from_origin()
        5.0
        """
        
        sum_of_squares = 0
        for coord in self.coords:
            sum_of_squares += coord**2
        return sqrt(sum_of_squares)



Special Methods

Classes can implement certain operations with special method names. 
In our code example, we have a Point class. Here we introduce four special methods. The __init__(), __str__(), __eq__(), and  __repr()__ methods.

 def __str__(self):
        
        return str(tuple(self.coords))
    
    def __repr__(self):

          return "Point({})".format(self.coord)        
    def __eq__(self, other):
          
         return ( # parenthesis for grouping across lines
            isinstance(other, Point) and # make sure other's a Point and
            self.coord == other.coord # check whether coords are equivalent
            )



Inheritance
    Another concept of object oriented programming is inheritance. Inheritance is when you create a general class (usually called the parent class) and then create sub-classes (usually called child classes) that use (inherit) methods and attributes from the parent class. When you intend to make your code more flexible and efficient, it's good way to use inheritance. Since you can use common methods and attributes in the general class for many sub-classes instead of re-writing the same code in every sub-class. Here is some code the an example of inheritance.

class A:
   def g(self, n):
      return n
      
   def f(self, n):
      return self.g(n)
      
class B(A):
   def g(self, n):
      return 2 * n

a = A()
b = B()
print("a.f(1): {}".format(a.f(6)))
print("b.f(1): {}".format(b.f(6)))

>>> 
a.f(1): 6
b.f(1): 12
>>> 


Impression for OOP

    In this course I’ve learned that Python is an object-oriented programming language, it is described that in OOP, ‘object’ is consisted of fields, which includes variables(contained in their object or class) and methods, which are the functions(contained in class). These independent objects are able to be reused, this ability is the feature of OOP. Actually, I have already learned something about Class in computer science 108 last semester, which helps me a lot to understand OOP but I am still a little bit confused about it. 

What I have already learned in class is that how to create different classes and define plenty of methods. And class has Inheritance, which means when different classes are called in other classes, they(subclass) inherit the properties from their original classes(parent class). When Danny was talking about OOP, I found that the built-in property() function in Python is hard to grasp. When I create an instance of Point, will it call property() function and then _set_coord(), _get_coord() are called? Does the self.coord have the same memory address as the Property object coord since there is only one “coord“ in the namespace? 

After going to Dannie's office hour before Term test 1, l got the answer of my questions. Access to coord is delegated to property, so _get_coord and _set_coord are called when I create an instance of Point. And self.coord and the Property coord both have the same memory address.

Friday, February 6, 2015

WEEK 5 SLOG

At the first few weeks, I feel stressed for studying CSC 148. The course is so compacted with lots of labs, slogs and assignments. I need to spend unlimited time on studying the course. The most biggest problems are that l cannot come up with an idea to write a code(the answer of a tricky question). l think that  l should boost the efficiency of thinking out of the solutions of questions. The main reason for this is that l didn't grasp the knowledge that l learned in lecture. l think the only way of solving it to do more practice, like the extra exercises in labs, as well as asking help for Ta or professor. In this week, we just learn the new thing relating to unittest, actually l feel confused about this concept. For example,  l don't know what’s the meaning of the code


    def testIsEmpty(self):
        '''Test is_empty on non_empty Stack.
        '''

        self.assertFalse(
            self.stack.is_empty(),
            'is_empty returned True on non-empty Stack!’)



Behind after  self.stack.is_empty(), why 'is_empty returned True on non-empty Stack!' be added?
Next week, we will learn unittest more deeply. Maybe l will understand.

Friday, January 30, 2015

WEEK 4 SLOG

   In this week, I learn the concepts about recursion on nested lists, recursion with turtles.

   We start to use recursion to write functions like sum_list and depth. These functions are required to implement actions to add or calculate depth of list in nested lists. Usually we build the function using list comprehensions. It is not a difficult concept to understand and I really enjoy to learn and use when writing code. However, one thing frustrates me is that some function call itself in list recursion. I put the example function code below. The problem is that I cannot understand if L = [1, [2, 3], 4] ) , when it enters the if statement and return 1 + max([depth(x) for x in L]). During the loop (list comprehension) , when x is any number or list in L, it will call depth(x). When x = 1, it enters else statement and return 0. This is the big problem that I catch with. In my view,  the function will return 0. But the truth is that after recording depth(0) = 0, the function will continue to implement list comprehension. In order to figure out my puzzle, l ask my classmate and then understand . Since calling depth(1) is in the process, it will not return and exit. I think it is so helpful  and fast for me to ask classmates relating to problems of learning. They can give you detailed answers.

   Furthermore, I think l am not confident  about the material that l learn in this week, because l did take more practice(using them to write some functions). In the weekend, l plan to do some by writing the past midterm paper.

def depth(L):
    ''' (list or non-list) -> int

    Return 0 if L is a non-list, or 1 + maximum
    depth of elements of L, a possibly nested
    list of objects

    >>> depth(3)
    0
    >>> depth([])
    1
    >>> depth([1, 2, 3])
    1
    >>> depth([1, [2, 3], 4])
    2
    '''
    # find the bug!
    if isinstance(L, list):
        return 1 + max([depth(x) for x in L])
    else: # L is not a list

        return 0

Wednesday, January 21, 2015

Why geeks should write


The word geek usually describes a person who has excessive enthusiasm for and some expertise about computer science and internet technology(technologically oriented geeks). Such group of people invest unlimited time in writing code and designing softwares. Geeks tend to operate in research departments, laboratories and support functions. They master the latest and most cutting-edge internet technology, so they can easily solve a complicated problem related to computer simply by a piece of code, or a program. It is very normal for geeks to use computer to write code using different programming languages, like python. If they do not write, obviously they won’t be a geek. Since geeks often indulge in developing software or learning new computer technology, they would rather sacrifice their own social time to do this. Not only do geeks write code, but they intend to share their technology and thought. If they don't communicate with others, they will not share their achievements to others,the techniques they created will not be spread. Now, geeks play important roles in developing global economy and society, they increasingly occupy senior corporate positions, and wield considerable commercial and political influence. The most famous geek is Bill Gates, the CEO of the world’s largest technology firms, all most every family in the world use Microsoft. Thus, such kind of geeks need to communicate to their colleagues or subordinates in order to designing fabulous softwares or internet products. I want to show another example Facebook, it is so hard for only one person creating such an amazing website. Geeks should write not only because writing codes, but communicating with others for promoting the development of the computer technology.