Wednesday, 25 February 2015

slog for week 8

This week we are learning about binary trees, in which each node only has at most two children.
 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

The use of the last line is smart!

Once we knew what a binary tree is, we learnt some methods used in this structure, for example, to evaluate it. The use of eval is said to be important, as in this line:
return eval(str(evaluate(b.left)) + b.data + str(evaluate(b.right)))

eval(...)
    eval(source[, globals[, locals]]) -> value
    
    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

However, I still have problem understanding how to use the 'eval' function. What does global and local refer to? I think I'm going to ask the TA in tomorrow's practical.

Furthermore, I learned the three orders, which are inorder, preorder and postorder.
Inorder is from left to right, as it was given in the class:
if root is None:
        pass
    else:
        inorder_visit(root.left, perform)
        perform(root)
        inorder_visit(root.right, perform)

Preorder is to evaluate from the root to the leaves, which goes like this:
        perform(root) 
        preorder_visit(root.left, perform)
        preorder_visit(root.right, perform)
And postorder is skipping the root and evaluate the leaves first, which I find a little bit hard to keep track of while tracing the order using a picture. However, it gets a lot easier just using the codes. That's to say, well, computer is smarter than me...
        preorder_visit(root.left, perform)
        preorder_visit(root.right, perform)
        perform(root) 

I also find it interesting that a recursion can be written in the way above and not necessarily using the form of return (...(c) for all the c in ...)

Above are the things I've learned this week, and more left to do for tomorrow's practical.
Fighting Dark Fox! 
Ciao!

Dark Fox

Saturday, 21 February 2015

slog for week 7

    This is reading week!
    Looking back on week 6, I have learned some interesting but also difficult things about tree.
 I have learned a lot of terminology. As a reminder, a tree has root, nodes, edges, leaves and subtree.

A path is a sequence of nodes n1, n2,..., nk, where there is an edge from ni to ni+1. The length of a path is the number of edges in it. The path is unique and it has no cycles.

The height is 1 + the maximum path length in a tree. A node also has a height, which is 1 + the maximum path length of the tree rooted at that node.

The depth is the height of the entire tree minus the height of a node is the depth of the node.

The arity or branching factor is the maximum number of children for any node.

After learning the terminology, I was taught to design codes to count leaves, count nodes, calculate the height and so on. An important method we used was recursion. First detect the base case, and then write the code for general case involving recursion. I could understand the code if it was already written, but it was hard for me to write recursion myself. In the practical this week, my partner and I only worked a few out with the help of our TA and piazza, which was so sad. Understanding what we should do was not the hard part, it was how we should do it that mattered. I think I still need some time to think about this carefully and try to catch up. If I could get the access to the answer to the practical after the every practical is done, that would be of great help to my study. After all, we first learn to imitate and then to think independently. I still need some more examples to grasp the clue of doing this.

Also I learned a format:
self.children = children.copy() if children else []
This is a functional 'if'. it means copy children if not none. The reason why we need to copy children 
is that we don't want to make change on the original data so that our counting method will not affect 
anything. 

I will work on recursion more and get a thorough understanding. I believe I can make it!~

Ciao my friend,
Dark Fox

Wednesday, 11 February 2015

Slog for Week 6 on Object-Oriented Programming Concepts(want to be marked on)

    When I first saw this topic, I had totally no clue what I am going to write. Object-oriented programming, what does that mean? I looked it up online, and it turned out that I have been dealing with this for a long time without even realizing what it is called.
     Let's start with class. Class is an object that can be created by ourselves. So far I've learned superclass and subclass, which are like parents and children. The children can inherit, extend or override the parents' methods. It is really convenient to have several subclasses to implement the super one. In this way, the whole program is clear and flexible, we can edit the subclass without changing the superclass and work on more details specific for each subclass. A subclass can literally inherit everything that is in the superclass. Whenever a change is needed, it can just modify the relating method by either extending or overriding. Overriding is just write the method again ignoring the superclass while extending is to cite something from the superclass and extend more codes for that. And don't forget to raise an NotImplementedError when the superclass is not able to define a method without a subclass. Just to take up the space for the subclasses to override.
    So what is a method? According to my understanding, a method is a piece of code associated with the class, while a function is independent of the class. The basic methods I have learned include __init__,  __str__,  __repr__,  __eq__, __contains__...  

For __init__, we have to be careful what variables should we put in the bracket: if the object comes with the parameters, then those parameters should be included as variables in the __init__bracket.
For the parameters we assign to a class, then we can simply include such parameters along the way.
I know my explanation is awful, let's use an example:
 def __init__(self, player):
        ''' (GameState, str) -> NoneType
        
        Initialize new game state self to have state which player plays next
        and a list for legal moves.
        
        >>> g = GameState('computer')
        >>> g.state
        'computer'
        >>> g.legal_moves
        []
        '''
    
        self.state = player
        self.legal_moves = []   
This is from assignment 1. Here the list of legal moves is something the object is not born with, it's gained along the way, so we just include it rather than putting it in the bracket.

Then, to distinguish __str__ and __repr__, below is a useful example:
  import datetime
  today = datetime.datetime.now()
  >>>str(today)
  '2015-02-11 09:56:20'
  >>>repr(today):
  'datetime.datetime(2015, 2, 11, 9, 56, 20)'

In short, __repr__ is to make be unambiguous and __str__ is to be readable.

And also,  for __eq__, it's not just all parameters should be equal to each other, we should also include the comparison of the class of two objects, using isinstance:
   return is instance(self, other) and self.a == other.a...
This need to be remembered, since I have made a mistake on this.

And with __contains__(do not forget the 's' at the end), we can simply use 'a in b' rather than 'b.__contains__(a) ' after defined.

It's important to implement the classes we created with the methods above, they can make your future steps a lot easier.  

Above is all I can think of object-oriented programming concepts. 

Tschüss!

Dark Fox


Monday, 9 February 2015

another slog for week 5

   Well, I just saw on the course website that we need to write our impression on tracing recursion, I hope it's not too late.
    Recursion, an interesting idea, which requires a good thinking and can simplify the loops by a lot. It's much like looking at yourself in mirrors and get repetitive image. The thinking process, namely the tracing, is important in recursion, since the language here is a lot more concise.

below is a brief example of recursion shown in practical





def nested_concat(L):
    ’’’(list or str) -> str
    Return L if it’s a str, if L is a (possibly-nested) str return
    concatenation of str elements of L and (possibly-nested) sublists of L.
    Assume: Elements of L are either str or lists with elements that
            satisfy this same assumption.
    # examples omitted!
    ’’’
    if isinstance(L, str):
        return L
    else: # L is a possibly-nested list of str
        return ’’.join([nested_concat(x) for x in L])
  1. nested_concat(’five’) --> ’five’ # since isinstance(’five’, str)
  2. nested_concat([]) --> ’’.join([nested_concat(x) for x in []])
            --> ’’.join([]) # there are no x in []
            --> ’’          # that’s what join does to empty list
  3. nested_concat([’how’, ’now’, ’brown’])
            --> ’’.join([nested_concat(x) for x in [’how’, ’now’, ’brown’]])
            --> ’’.join([’how’, ’now’, ’brown’]) # traced nested_concat(str) before
            --> ’hownowbrown’ # join does ’how’ + ’now’ + ’brown’
    
  4. nested_concat([[’how’, [’now’, ’brown’], ’cow’]])
            --> ’’.join([nested_concat(x) for x in [’how’, [’now’, ’brown’], ’cow’])
            --> ’’.join([’how’, ’nowbrown’, ’cow’]) # traced nested_concat(list of str)
    
                                                    # and nested_concat(str) before
    
            --> ’hownowbrowncow’
    
  5. nested_concat([[’how’, [’now’, ’brown’, [’cow’]], ’eh?’]])
            --> ’’.join([nested_concat(x) for x in [[’how’, [’now’, ’brown’, [’cow’]], ’eh?’]]
            --> ’’.join([’how’, ’nowbrowncoweh?’]) # believe docstring for str and possibly-nested
    
                                                   # list of str or possibly-nested...
    
            --> ’hownowbrowncoweh?’
    
    
    
    
    When I first saw this example in practical, I raised a question. While tracing the 5th example, is put join([’how’, ’nowbrowncoweh?’]). which I think is wrong, and it turned out that I was right. Our course materials sometimes also make mistakes, eh?
    through the tracing process, it is also important to remember not to trace too much, just simply use the result from before, otherwise the tracing will be so long... well, that's the difference between a computer and a human brain, we don't want to make things complex and that's why we developed computer programs.

    So long, Ciao!
    Dark Fox

    Ps: don't forget tp keep track of the brackets while tracing, and make sure what type of object you are using!

Saturday, 7 February 2015

Slog for week 5

       This is the 5th week of school, and we had our computer science's term test , which worth 10%.
       I was kind of worried at first before the test when I took a look at the past test. There was questions about stack on that, but I've only just learned stack on Monday. I finally realize how important is the practical, it helps me understand and use the concept better. However, the good thing is , stack was not on the test. And after that, in our practical, I got to use stack and queue, which helped me a lot, and those don't seem hard any more. Well, last in first out, first in first out, I could actually use my imagination of what a stack and a queue are like.

As the pictures show, we can only take the last added stone off the stack, but for a queue, the person comes the first should go first, since he has been waiting for so long.

Using the pictures and imagination to learn is really a good idea. Being relating the new knowledge to some everyday stuff make it a lot easier to memorize. No, I don't even need to memorize a thing , whenever I see the same thing, I can easily repeat the understanding process and I'm sure I won't get it wrong.


Back to the test, hmmm, I would say it's not hard. However, a friend of mine told me that we're probably wrong for the first question, to make the dictionary as {'email': 'respond'} rather than {'yes': ['...']} I'm not sure, well, i forgot what was the question exactly. gonna turn back to this later when I have my test back. I'm now crossing my fingers for that. Amen!