Sunday, March 2, 2014

Week 7

This week was the week of our test. To be honest, it was not bad, but as the results came back I was a little disappointed with how I did. I should have done better and recognized exactly how if statements work. As a quick review to my future self, the if statement covers the WHOLE line so it's not something like
1 + (ternary if statement), which is what I did, but instead the entire line is the ternary if. This means it works out to be something like:

1 + something if something else something

The 1 + something is the first result, not just "something". Once again, I am somewhat disappointed in myself.

Anyway, onto recursion. Throughout most of the course, we've been slowly learning recursion step by step. The simplest way I could describe recursion to someone is that recursion is a type of function that calls itself somewhere in the body. It is used in order to reduce incredibly complex codes to the smallest "base case" in order to accomplish what you want the function to do. This is incredibly useful for things like nested lists when you're trying to find things like objects within nested lists or perhaps the maximum depth of nests within the argument. Of course, recursion is not simply limited to things like these but it is as good example to get a beginner started.

How the body of a recursive code works is that there is always what we call a "base case", as mentioned above. This base case is the simplest case, and is the only case that is evaluated instead of calling the recursive function again. Every other case will be a recursive call in order to try and simplify the code into the base case, and make things easier. An example given by our professors was the sum of the numbers inside a nested list, which can be found here.

http://www.cdf.toronto.edu/~heap/148/W14/Lectures/danny/W2/rec.py

def sum_list(L: list) -> float:
    """
    Return sum of the numbers in L.

    L --- a possibly nested list of numbers.  L, and all sublists, are
          non-empty

    >>> sum_list([1, 2, 3])
    6
    >>> sum_list([1, [2, 3, [4]], 5])
    15
    """
    return sum( # sum of...
        # sum of sublists or else non-list elements themselves
        [sum_list(x) if isinstance(x, list) else x for x in L])

As you can see there is a base case, where if the object that the list comprehension comes across is not a list, then you simply add the numbers together. However, if the object IS a list, then you have to call the function again and go from there. Once again this is a very basic example.
There is still much to learn about recursion, but I think I'm really starting to get it.
Update:
the ternary if's are still affected by brackets so as you can see, the code will return different values depending on if and where you place the brackets.

a = [] 1 + (1 if isinstance(a,list) else 0) 2 1 + 1 if isinstance(a,list) else 0 2 1 + 1 if isinstance(a, str) else 0 0 1 + (1 if isinstance(a, str) else 0) 1

Sunday, February 16, 2014

Week 6

This week was pretty hectic for computer science. Not so much the lectures, but moreso an emphasis on the assignment 1. I had been stuck on part 5 for so long, and I didn't know what to do. Therefore, I had to go to one of the help sessions in order to finally get a clue and finish it. Thankfully, I managed to get it done (and the best solution, too) before the deadline.

As for the lectures, we went over trees (more recursion). We learned many things like leafs, nodes, subtree, height, and went over how to write a recursive function to gather this data from a Tree class. I feel that I'm slowly but surely getting recursion better and better, but it can still be a headache sometimes.

Although I have a generally feel towards these topics, I still believe I need to work harder in order to get a better grasp of recursion. Good luck to myself, I suppose.

P.S. the lab was fairly easy this week. However, I need to work on writing test cases. They can be confusing sometimes. >.<

Sunday, February 9, 2014

Week 5

In this week, we went over recursion some more, and I really think I'm finally starting to get it. On Monday, we went over the process of writing a recursive program for the movement of cheeses on three stools. I'm sure this is going to be useful for my assignment, but I'm still worried about how to write a program for four stools. Anyway, on Wednesday, we touched on names and where local, nonlocal, global, and built in module names stand on the name hierarchy.

def scope_test():
    def do_local(): # nested function --- only available inside scope_test()
        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)

nonlocal turns the name spam into a local name inside the function scope_test
global turns the name spam into a global name in the entire module.

As for our lab, we worked on more recursion. I was happy that I was able to finish both of the required functions as well as one of the bonus ones. Here is the code if anyone is interested.

def find_num(SL: 'SearchList', n: int) -> bool:

    if n < SL[0]:
        return (find_num(SL[1], n) if isinstance(SL[1], list) else False)
    elif n > SL[0]:
        return (find_num(SL[2], n) if isinstance(SL[2], list) else False)
    elif n == SL[0]:
        return True
    
def freeze(x: object) -> object:

    if isinstance(x, list):
        return [freeze(item) if isinstance(item, list) else item for\
                item in x]
    else:
        return x    

def rev_string(s):

    string = ''
    for x in range(len(s) - 1, -1, -1):
        string += s[x]
    return string

p.s. we touched on methods a little bit more. 

class a:
    def b():

        return 2

if I did a.b(), it would return 2.
however, if I did this:
c = a()
c.b()

I would get an error because now the class a has an argument now, which is the name c.

Thursday, January 30, 2014

Week 4

Week 4 was a quiet week, I suppose. On Monday, we simply took a look at our first assignment, which I've started already (done 70% but need a little help for the last bit). Also, we took a look at the nested list recursion problem.

On Wednesday, we went into detail about a "tree burst" recursion function. What this function did was that it created a tree-like drawing when running it. Obviously, this example was to further reinforce our understanding on recursion and the different ways it can be written.

The lab this week was also pretty informative. In addition to working on more Object Oriented Programming, we also worked on UnitTest, which was something that we never really went into in csc108.

All in all, it was a pretty dry week. I should probably look more into the properties function and learn how to fully implement it.

Sunday, January 26, 2014

Week 3

This week, we focused on what we call Object Oriented Programming. Essentially, from what I can understand, it basically means a focus on classes. The use of  "class" is to be able to focus the programming around an "object", hence, OOP. When creating the class, we can add methods to indicate the class(object) to do something. For example, creating a 'toy' class and then a 'play' method. In addition to creating new classes, we can also create a subclass (extended class) of a superclass (base class), which inherits all of the superclass' methods. Note, however, that the superclass' methods can still be modified in the extended class if you write the method in the superclass (check IntStack for example).

Exceptions were also made more clear this week, and the creation of new Exceptions by sub-classing the Exception class was also explained.

Other things learned this week:

Try: This function tests the following lines of code. If it reaches an exception it looks for an except statement further below that matches the exception, and then proceeds accordingly.

print Exception('string') prints the string

Class variables are variables that exist in class and are universal with all methods. This is where the property function comes in play

To reverse a list, [ : : -1] is used

__repr__ is used when representing a class. This means that when you type something like

>>> toy = Toy()

and then you type toy in the python shell like this,

>>> toy

you get something other than the default return
ex:
>>> Toy()

Saturday, January 18, 2014

Week 2

Week two was much better, in my opinion, as we started to focus on actual content. While much of the content were things that are still retained in my mind from last semester's csc108, there were a few things that caught my attention that were either new or different.

One thing that I noticed was that the way our professor likes to write type contracts is to do it in the parameters itself, using a colon to designate a type.
    ex: >>> def apple(colour : str) -> str:

I should quickly get used to this, because apparently that's what he wants us to do.

Another thing that particularly interested me was the usage of the property function in classes. It's something that prevents instances from changing, to make the initialized objects harder to modify. I'm still not quite sure how it works, but I plan on either going to a help session or going to the teacher to clarify this.

Finally, we learned recursion. So far, the examples are pretty basic. I'm sure the difficulty will ramp up soon enough, but luckily so far it's okay. Simply put, it's a function that calls itself.

P.S. the lab was okay. I felt that the instructions were not really clear, but maybe that's just me.

P.P.S list comprehensions were made more clear, set() function was shown, ternary if's shown.

list comprehension:
S = [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Set() 

Ternary if:
'true' if True else 'false'