Friday, February 27, 2015

Hi Trees!!!

Welcome back everyone! Hope you all have a great reading break and a lot of sleep :) First of all, I would like to indicate that I want my previous post about OOP being graded, and I would direct my wonderful TA (or whoever is reading this) to the OOP post here.

Okay, so let’s talk about what is new in class. We learned Trees!! In this post, I would like to summarize everything we learned about Trees, Binary Trees (BT) and Binary Search Trees (BST).
Let’s start with some terminologies.
Node: a structure, which may contain a value, a condition or represent a separate data structure (which could be a tree of its own).
Tree: a set of nodes with directed edges between some pairs of nodes.
Edge: connects a parent node to a child node
Each node has zero/more children (child nodes). A node has at most one parent.
Root node: The top most node in a tree and has no parent.
Leaf: node with no children.
Internal node: a node with one or more children
Subtree: tree formed by any node and its descendants and the edges connecting them.
Path: a sequence of nodes n1, n2…nk where here is an edge from ni to ni+1
length of a path: the number of edges on it
height of a tree: the maximum path length + 1
depth of a node: height of the whole tree – height of the subtree rooted at that node
arity/branching factor: the number of max children for any node




That is a long list!! Hopefully, these images can give you a visual representation of the data structure tree. 
















Here is the __init__method for the tree class we defined. Notice we use a list to represents the child nodes of a parent node





I would like to move on to BT and BST.
Binary Tree: a tree with branching factor 2. We call the children left child and right child.

Here is the __init__ method for a BTNode class. Notice we separate the two child nodes as left and right.




Binary Search Tree: a binary tree such that for every node, its value is greater than all the values in its left subtree and less than all the values in its right subtree.
BST is a good tool to use when performing operations like searching or sorting, because we can utilize the order established in a BST and cut operations instead of visiting every node.

Here is an example of a binary search tree.












When implementing functions dealing with BT and BST, it is important to keep in mind that every node has two children. Also, each subtree as well is a BT or BST. 
I do find this week’s lab changeling and interesting. With the help from my TA, I was able to solve most of the problems. I would like to include two examples here that I find extremely beneficial for my understanding of recursion and BST and how I was able to able to come up with a solution at the end.

1. implement list_longeset_path, which will list the data in a longest path of a tree rooted at a BTNode.
Here is how you can think of this problem:
base case: return [] when node is empty
recursion: return the value at this node + the longest path from the subtree rooted at the left child if it has a longer path than the subtree rooted at the right child or vice versa.

I was stuck because I did not think of putting the recursive calls before the return statement. Yet, it is completely legal to do so and it makes the code more clear and presentable. In fact, sometimes you have to do it in this way in order to solve a problem!


2. Let's look at an example about BST.
Implement list_between, which will take a binary search tree and return a list of its data between start and end, inclusive.

This is a perfect example that demonstrates how we can utilize the property of BST and make the algorithm efficient without visiting unnecessary nodes. 
suppose we have a BST like this, call it t,  and we call list_between(t, 5, 9). We start from the root node 8, 5<8<9, so no cutting can be made. This is because both left child and right child have the possibility to be in the range 5-9. Now let's say we go to its left children, and we find that 4<5. We now know that we do NOT need to examine the left child of 4, since anything less than 4 will also be less than 5. The same argument holds if we find a node whose value is greater than end, we do NOT need to visit its right child.
In summary, we keep looking in the left branch if node value is greater than start, we keep looking in the right branch if node value is less than end. We include the node value if it is between start and end. Putting these into codes, we have
















These are the two examples that really help with my understanding of recursion and BST. I find that writing comments or summarize ideas into English is an extremely good way to help you get started on a new problem. That is all for this week. I hope you enjoy reading this and please comment below if you have any questions or just want to have a chat ;) 





Friday, February 20, 2015

Oops… Here Comes OOP

Hi there, I am back to my 4th slog. As I mentioned in my very first post, why geeks should write, programmers need to continuously reflect and summarize what they have learned and encountered in programming. Speaking of this, I think now is a good time for me to summarize my understanding of object-oriented programming, which is the most important concept we have encountered in CSC148 so far. 
Please feel free to correct me and fill in by commenting below, as I know there are a lot to include. Also, I am excited to hearing feedback; )

Object-oriented programming (OOP), as the name suggested, is a style of programming in which data and the operations are organized into objects. In other words, programmers focus on objects instead of the implementation details. To understand OOP, I will walk you through a couple of key concepts with examples.

First of all, let’s talk about object. An object can be anything in the real world, like a pen, a car, a dog, or a subtract square game state. Each object bundles together attributes (data stored in variables) and behaviours (methods that perform tasks). For instance, a dog object have attributes: weight, colour, breed; and behaviours: barking, wagging tail. Now, let me give a formal definition of object.
Object: A basic entity in Python that models a thing or concept in the real world, which contains attributes and behaviours.
In fact, every value in Python is an object, like str, int, list and dictionary.

Next, we look at class.
Class:  A template or blueprint for the objects of similar types.
You can think of class as a type or a collection of objects as well.

Another important concept in OOP is inheritance.
Inheritance: A mechanism involves classes inherit (get) commonly used attributes and behaviours from other classes. A subclass (child) class, by default, inherits all the methods and attributes of the super (parent) class.

To illustrate these concepts, let’s say you want to create a circle, a square and a triangle. These are different types of shape, and you know they will be drawn at a certain position with a certain area. Instead of creating them separately, we will use inheritance and define a parent class, Shape.

As you can see in the doctstring , Shape is an abstract class that cannot be instantiated (I’d better define instantiation)
Instantiate: To create an instance of a class.

Notice that the get_area method raises a NotImplementedError, this is because different shapes have different ways of calculating the area, and we do not know how to calculate the area yet.

Now, if we want to define the Square class, we can simply make it a subclass of Shape, so that it can inherit all the attributes and behaviours of Shape.



Here, Square extends Shape, by adding the attribute base. At the same time, Square overrides Shape, by re-defining the method get_area. In fact, when we implement the special methods, __str__, __eq__ and __repr__ in a class, we are overriding these methods as well. The reason is that these methods are inherited from the ultimate ancestor, object.

To access the attribute or method of a specific object, follow the format:
Thingee.attribute / thingee.method()
Remember that Python starts by looking at the most specific part of the object and if it is not found, Python goes “up” to its ancestors.



As you probably notice, inheritance is a powerful structure that simplifies the code by giving Square all the attributes and behaviours that a Shape should have, yet allow it to focus exclusively on the features that make it unique. In fact, inheritance provides reusability, which means adding additional features to an existing class without modifying it. With this powerful tool, codes can be reused to create different kinds of shapes, like this.


The Java Tutorial website provides a great list of the benefits of OOP programming that I really want to share with you (the website is here).



To summarize, OOP programming is a revolutionary concept that enables problems to be analyzed in terms of objects and communication between them. With OOP, reusability of codes is maximized; different objects can interact with each other without knowing the specific implementation details. Below are pictures that further illustrate OOP.
Hope you enjoy reading this and please don’t hesitate to comment below.

Happy Reading Week Everyone!!!!

Monday, February 9, 2015

Recursion..Recursi…Recur…Rec…R…Let’s trace recursion!!

Hello all, I hope everyone is having a great week after finishing our first term test and assignment. This week’s learning material is one of my favourite, recursion. This is not the first time that I have seen recursion, since I have learned it in high school. Yet, I can still recall how astonished I was when I was first introduced to recursion. Calling yourself recursively and then you can solve a complicated problem? This is mind blowing. Now, I have come to understand the concept of recursion and how powerful it can be to solve problems in a simple and elegant way. So, why don’t we start a journey to discover the beauty of recursion?

First of all, what exactly is recursion? Recursion involves a function calling itself inside the function body. Its basic concept is to break a complicated problem into smaller and smaller sub problems until you get to a simple enough problem that can be solved easily. This idea sounds magical, but to understand recursion fully, we need to work through an actual example. Consider the code below.



Tracing recursion can get really bothersome if we start with a random example. The key point is that we need to trace recursive calls progressively, which means starting with depth level 1(or the simplest situation), then moves our way up to depth level 2, 3, and so on.
Here, the simplest example is when L is an integer instead of a list. Under this condition, nm simply returns what L is. This is also called the base/general case, since it provides a condition to stop the recursive callings.
>>> nm(6)
6
Then, we look at what would happen if L is a list with depth one.
>>> nm([1, 3, 7, 5, 2])
è max([nm(1), nm(3), nm(7), nm(5), nm(2)])  #we know how nm performs on an integer, so we get

è max([1, 3, 7, 5, 2])
7
Now, trace the function when L is a depth-two list
>>> nm([1, [3, 7], 5, 2])
è max([nm(1), nm([3, 7]), nm(5), nm(2)]) #we know how nm performs on a depth-one list, it returns the maximum number in the list.
è  max([1, 7, 5, 2])
7
Continue to trace a depth-three list.
>>> nm([1, [3, [2, 7], 4], 6])
è max([nm(1), nm([3, [2, 7], 4]), nm(6)] #we know how nm performs on a depth-two list, it returns the maximum number
è max([1, 7. 6])
7

As you can see, the most important part in this tracing process is that, we trace to the point when we know what would be returned instead of going to the base case every time. This saves us from getting really messy recursive calls, and helps with the understanding of how to come up with a recursive solution. The recursive thinking process somehow assemblies the mathematic concept of induction, which is to solve the problem with order n, assuming the order n-1 case works. Therefore, when you implement a recursive solution, you want your calling to change the problem state to one that is a little easier to solve every time. By doing this multiple of times until we reach the simplest problem that we have an answer for, the original problem can be solved by working our way backward through a series of calls. (This is why we start tracing from the simplest problem, then go up with depth 2, 3, 4…) In this sense, the base/general case plays a crucial part in recursion, since it identifies the order 1 case and stops recursion when necessary. Without the base case, recursion will be an infinite loop that has no meaning.

To summarize everything, there are three rules that programmers need to follow when implementing a recursive solution (I visited one of my classmates' slog and found a useful website, these rules are taken from that website, the full article is  here, the slog that I steal this from is here)
1.     A recursive algorithm must have a base case
2.     A recursive algorithm must change its state and move toward the base case
3.     A recursive algorithm calls itself, recursively

Tracing recursion is not hard to understand if you follow the process I did above. Once you do the tracing for a couple of different examples by yourself, you will understand recursion more thoroughly (like me after lab4). Recursion is such a powerful tool that can solve a really complicated problem by repeatedly solving a simple version of the problem. It is by far the most elegant solution I have ever seen in computer science, and I am excited to discover more about it. Below are images created by recursion. If you are interested in this stunning concept, start tracing today!!
 






Tuesday, February 3, 2015

My impression of first few weeks in CSC148 -- WEEK4

My experience in CSC148 for the first three weeks was rather relaxing and enjoyable, except the fact that assignment1 is due in week4 and there is a test coming up next week. The course materials were pretty straightforward for me, since I had previous programming experience in Java. However, there are several cool Python features that Java does not have which have caught my eyes on. In this post, I will briefly explain the concepts we learned in class and comment on my experience of working on assignment1 with my group.

The materials we learned in class include class design, property, inheritance and list comprehension. Let’s begin with list comprehension, which I find an interesting feature in Python. Basically, list comprehension is a simple way to shorten your code when implementing a list involving iterations. It has the general format [<expression> for x in iterable]. The beauty of list comprehension is that it simplifies your code into one single line instead of writing every iteration in different line, which can get really messy especially in a nested loop. Consider this example,









And the result is here






These two implementations produce exactly the same result, but look at how simple and elegant the fist implementation is. In fact, I have learned to try to keep my program as simple as possible, because I think it will benefit me when codes start to get longer and hard to follow. Now, list comprehension just becomes the handy tool.

Inheritance is the biggest concept that we practiced using in assignment1. Even though it is not a new concept to me, I still find it pretty challenging when deciding on the structure of our program. Inheritance involves grouping common attributes and behaviors in a parent class, so that every child class can use or modify them without having to rewrite the common stuff over and over again. For assignment1, my teammates and I had difficulties on how to implement the game_view class without making it specific to subtract square. At first, we put a bunch of codes in
if __name__ == ‘__main__’, but later realized that we need to break down these codes into methods that can work for every game. Yet, we had no clues how to do it. To overcome this problem, one of my teammates went to the aid center and I consulted Danny after lecture on Wednesday. After our attempts to seeking for help, we finally came to understand the proper way to implement game_view, which uses instances of game_strategy and game_state.

Overall, my experience of working with my assignment1 group was delightful and engaging. At first, we decided to each write a version of the program and improve on the best one out of three. However, it became difficult and time consuming when you want to improve or work on the codes that are not written by you, simply because of the differences in implementation. Even though it took me a long time to understand the codes of others first and then comment on my opinions, this process provided us with a variety of ideas and the widest collaboration we can get from each other. I learned a lot from my teammates and I appreciated their efforts of trying to make the assignment as good as possible. Yet, I noticed the subjectivity of this assignment, so I am still unsure about whether or not our implementation or structure is the ‘correct’ way to tackle this program. Thus, I am anxious to hearing feedback from the TAs.

Lastly, I want to write a little reflection for the first quiz I had, which gave me a score of zero. I have to say that I am surprised by the result, because I consider it a fairly simple exercise. But it turned out that I did not read the question carefully: the question asked for an __init__ method for the InventoryItem class, but I misinterpreted as asking for a InventorySystem class. I have learned to be more careful when reading long questions, since understanding the question is the first step of solving it.

Thanks for reading another long post (can’t believe I wrote this long lol), I will see you next week!