Sunday, 23 February 2014

Week6: Trees

    This week we are introduced to Trees. They have unique properties so that they can build expressions and even make wise "animal tree".

     The tree is similar to linked lists. Start with terminologies, it consists of nodes(the top one is root). The paths between parent and children are called edges; the length of edges is the number of edges. Height is the maximum path length from the leaf(the node that has no children) to root. Likewise, the level of the tree is all the nodes that have same distance to root. The last fancy word is arty or branching factor, which means the maximum children within any node. 
 
    There are basically three ways of traversal for tree expression. They are pre-order(prefix) traversal, in-order(infix) traversal and post-order(postfix) traversal. As we want to print the contents of a tree in specific order, we need to write up functions. For a binary tree, the followings are the examples of the three different orders.
def print_tree(tree):
    if tree is None: return
    print(tree.cargo, end=" ") #cargo is the value
    print_tree(tree.left)
    print_tree(tree.right)
def print_tree_postorder(tree):
    if tree is None: return
    print_tree_postorder(tree.left)
    print_tree_postorder(tree.right)
    print(tree.cargo, end=" ")
def print_tree_inorder(tree):
    if tree is None: return
    print_tree_inorder(tree.left)
    print(tree.cargo, end=" ")
    print_tree_inorder(tree.right)
    The key for pre-order traversal is always print root(cargo) of a TreeList at first and then go into the left subtree which is a recursive call, and print its cargo and the left subtree of it until the tree is None, it exit and return to previous call to execute "print_tree(tree.right)" which is another similar recursive call. In a general view, it will print the root, the entire left subtree and the entire right subtree. For post-order traversal, it print from the left subtree to right subtree, and finally root. Obviously, the in-order traversal prints in an order of left subtree, root and right subtree. These different traversal make Tree neat, functional and well-organized.

    On the other hand, we are learning how to build an expression tree. By giving with a list of string which a mathematical operation expression, we rearranged them in an ordered way according to different priorities of operations. It is important to consider multiplying, addiction, and even parentheses. Another thing to remind, to avoid python quit unexpectedly, we would better write exceptions to raise error.

    Last but not least, the animal tree is something that I found like an interesting and cute game. After the training by ourselves, it learns new knowledge. I would like to put the long code below for appreciation.

def yes(ques):
    ans = input(ques).lower()
    return ans[0] == "y"

def animal():
    # Start with a singleton
    root = Tree("bird")

    # Loop until the user quits
    while True:
        print()
        if not yes("Are you thinking of an animal? "): break

        # Walk the tree
        tree = root
        while tree.left is not None:
            prompt = tree.cargo + "? "
            if yes(prompt):
                tree = tree.right
            else:
                tree = tree.left

        # Make a guess
        guess = tree.cargo
        prompt = "Is it a " + guess + "? "
        if yes(prompt):
            print("I rule!")
            continue

        # Get new information
        prompt  = "What is the animal's name? "
        animal  = input(prompt)
        prompt  = "What question would distinguish a {0} from a {1}? "
        question = input(prompt.format(animal, guess))

        # Add new information to the tree
        tree.cargo = question
        prompt = "If the animal were {0} the answer would be? "
        if yes(prompt.format(animal)):
            tree.left = Tree(guess)
            tree.right = Tree(animal)
        else:
            tree.left = Tree(animal)
            tree.right = Tree(guess)
(from: http://openbookproject.net/thinkcs/python/english3e/trees.html)

    The part I found difficult to understand is that only the leaf refers to an animal, and the other nodes actually contain questions. The function has multiple levels for completion which eventually creates someone we can communicate with.

    Keep working and hope everything runs smoothly(especially my code)!!

Sunday, 9 February 2014

Week5: Tower of Hanoi, Scopes and Namespaces

    Start working with Assignment 1, it actually requires lots of thinking and efforts. The main purpose of this assignment is about moving cheeses on stools and also to find the minimum steps. Furthermore, it is involved in recursion and I think that is the most difficult part.   

    The code below reveals how to move cheeses on three stools:
def move_cheeses(n: int, source: int, intermediate: int,
                 destination: int) -> None:
    """Print moves to get n cheeses from source to destination, possibly using intermediate"""
    if n > 1:
        move_cheeses(n - 1, source, destination, intermediate)
        move_cheeses(1, source, intermediate, destination)
        move_cheeses(n -1, intermediate, source, destination)
    else: # just one cheese --- no recursion required!
        print("Move top cheese from {} to {}".format(source, destination))
    As we have practiced so far, it has a base case which print "move top cheese from source to destination", and after tracing the general case, the function ultimately will print every steps it used of moving cheeses from the first stool to the last stool. What the general case does is moving all but the bottom cheese from the source(1st) stool to the intermediate(2ed) stool and having destination(3rd) stool as intermediate stool; it is recursive. Next, move the bottom cheese from the source(1st) stool to the destination(3rd) stool; it is not recursive as n is not greater than 1. Lastly, move all the cheese on the intermediate stool to the destination, using the source(1st) stool as intermediate stool; it is recursive. 
    In our assignment, we need to move between four stools. This would greatly reduced the move steps because not like moving between three stools we have one intermediate stool now we have two. Therefore, to find how many cheeses will be moved in the first place in order to get minimum number of moves became a big challenge. Works on them really help me get better understanding on programming.


    Other things I found hard to understand are scopes and namespaces. They are new and abstract concept for me. According to the notes online, a namespace is "mapping from names to objects", such as built-in names, global names and local names, and each of them are created at different stages and have different lifetimes. Another important fact to notice is the local namespace is created when the function is called, and "forgotten" when the function exits. The orders in python are innermost scope (local), enclosing scopes (nonlocal), global, and built-in names. 
     The example below is about how global and nonlocal methods work and the clearer sight of namespaces and scopes. When we first assign spam = "test spam", it is local in scope_test(); "spam = "local spam"" is inside do_local(), therefore after the function is called, the value is forgotten, spam still refers to "test spam". After we nonlocal spam in the do_nonlocal(), we assign new value to spam, "spam = "nonlocal spam"" and it is still true in scope_test(). Moreover, global spam make "spam = "global spam"" true in global name spam. However, we still print local spam inside scope_test(). Finally, when we exit the scope_test(), the global name spam refers to "global spam".
def scope_test():
    def do_local():
        spam = "local spam"
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)
The output of the example:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
Thanks for reading!


Saturday, 1 February 2014

Week4: Recursion

During this week, we were taught about recursion. Recursive functions are important and efficient in python to solve complex problems. Understanding its concept, structure and usage is significantly important.


First of all, the difficulty of understanding recursive functions comes from its operation; a function calls itself during the function. We have to trace it until it reaches the base case to figure out how the entire function is been supported. If the function just run infinitely, it produces error. Thus, a recursive function must have its base case, which sets up how and when a function stop its recursive calls. The other part of the function is called general case. 

    Example:
                  def nested_depth(l: list) -> int:
                        return (1 + max([nested_depth(x) for x in L] + [0]) if isinstance(L, list) else 0)

The base case is "if isinstance(L, list) else 0", it makes the recursive function have an end point. No matter how deep the lists are, when it reaches the list that contains no inner list, the result of this recursive call will be 0. Next, it will exit and continue to execute the previous call, and once the previous call finished, it will back to the call before it, and finally the result is returned. 

    Trace nested_depth([14, 7, [5, [3, 17, 1], [2, 4], 6], 9]):

    (1). [0, 0, [0, 1, 1, 0, 0], 0, 0]
    (2). [0, 0, 2, 0, 0]
    (3). 3


Obviously, the body part "1 + max([nested_depth(x) for x in L] + [0]" is the general case. With a step by step analysis of a recursive function, the structure becomes clearer. "Recursive" is very different from "circular" and the key difference is recursion have base cases,  and we try to avoid becoming circular because it is meaningless. I found recursion is similar to a while loop to some extent, which both have a point to stop and run repeatedly. However, loops are not recursive.

Furthermore, recursive functions draw concrete images which are some beautiful fractals. That is an amazing work. In the given notes, I traced the function "koch".  


    Example:

def koch(t, order, size):
    """
       Make turtle t draw a Koch fractal of 'order' and 'size'.
       Leave the turtle facing the same direction.
    """

    if order == 0:          # The base case is just a straight line
        t.forward(size)
    else:
        koch(t, order-1, size/3)   # Go 1/3 of the way
        t.left(60)
        koch(t, order-1, size/3)
        t.right(120)
        koch(t, order-1, size/3)
        t.left(60)
        koch(t, order-1, size/3)
   
    Trace: koch(t, 2, 3)

    - koch( t, 1, 1)
    - t.forward(1)
    - t.left(60)
    - koch(t, 1, 1)
    - t.forward(60)
    - t.right(120)
    - koch(t, 1, 1)
    - t.forward(1)
    - t.left(60)
    - t.forward(1)

As we have seen, the function structure does not change much. To write a recursive function, first of all, we need to think about the base case, the most basic move, and then we write the general case to call the function recursively.

In the end, with the practices on labs and exercises, I become familiar with writing test cases and raising errors. Assignment 1 especially need lots of work on recursion and requires deeper understanding. Throughout the learning, programming turns out to be much more fun!!