Saturday, April 4, 2015

It is time to say GOODBYE...

This is my last slog for CSC148. HOW TIME FLIES!!!
Can't believe we are at the end of this course (with exam to come!), and this is going to be my last impression of this course :((
If you remember, I summarized my understanding of linked list in this post, and decided to do a comparison between linked list and normal list, which I haven't done so. I am going to do it here and also combine it with the last lecture we had about efficiency and bigO notation.
The comparison between a linkedlist and a noraml list is based on my knowledge about java, so please correct me if I state anything wrong.
As far as I know, a lot of people are wondering about why do we need a linked list data structure if we already have our normal list which perform exactly the same sort of tasks. Well, the truth is, depends on the task that you want to perform, sometimes it is more efficient to use a linked list, while sometimes a normal list may be better. To see why, let's first visualize how these two data structure look like.

Sorry that the picture says array cause  I took it from a java website. Basically, array is the same as a list in python.







1. Access an element.
For a list, we access each element through indices. However, for a linked list, we have to walk through the list via references. In the worse case scenario, the run time efficiency for a linked list is O(n), while for a normal list is O(1).

2. Adding/Deleting elements
Linked list allows us to add or delete element much easier than lists (I discussed how to insert an element in linked list in a previous post here) In a list, we would have to shift every element to make room/fill up space for the operation of adding or deleting. If the list is small, this is no problem, but if we have a really big list, this may take a really long time. Yet, in a linked list, the only thing we need to do is to create a new node and change one or two references to add that node or delete it from the linked list. In fact, performing operations like adding or deleting on a normal list has run time efficiency O(n), while on a linked list has run time efficiency O(1).
In sum, if we need to perform a lot of accessing operations and seldom insertion or deletion, then using a normal list is more efficient. On the other hand, if we need to perform a lot of insertion and deletion but seldom accessing operations, then a linked list is a better choice.

A last note about CSC148...
At last, I want to say that it has been a great pleasure to be in prof Danny's class. He is one of the best professors I have encountered in my first year at UFT. I really like studying CSC148 because I find that students in this course are really supportive to each other, whether it is through piazza or just answering questions in class. A big THANK YOU to my assignment group! I really enjoy discussing all those mind blowing recursions problems with you guys. There were times when we were  stuck and frustrated, but we shared our ideas, pose questions, support each other and finally we managed to finish everything! You guys are the best teammates I have ever had, and we have come across so many things that I am sure our friendships will last even if this course has come to an end.

I appreciate all the help from my fellow classmates, teammates, Tas as well as the professors. It is been a great semester studying with all these wonderful people. It is hard to say goodbye... but the farewell time has come, so...
 GOOD LUCK ON YOUR EXAMS EVERYONE!!! and I hope you all have a wonderful summer!!!






Saturday, March 28, 2015

Revisit Why Geeks Should Write

Hello ALL!!
This is my second last post and I would like to revisit my very first post, why geeks should write.
In my first post, I stated that the reason for programmers to write or keep a journal is for the purposes of communication, collaboration as well as reflection. Throughout this semester, I was able to demonstrate this idea by myself as I keep updating this slog. Now, I am more confident to say that writing surely is beneficial for programmers. I would like to reflect on my journey of keeping this slog and further explain why I think geeks should write, so please continue reading!!!

First of all, as a student who has been in Canada for only two years, language barrier is always a big challenger for me. Even though I may understand everything that was taught in class, sometimes I have trouble expressing myself. However, as I keep writing and summarizing course materials in this blog, I find myself more comfortable explaining ideas and concepts in English. As before, I may spend hours trying to put up one journal or slog,  but now it would not take that long any more. The truth is, my writing skills as well as speaking skills improve by keeping up the habit of writing blogs every week. As a result, I would strongly argue again, as in my first post, that writing improve programmers' communication skills in all perspectives!

Next, writing is crucial for computer scientists as it encourage collaboration. In fact, I regularly visit other students' slogs and leave comments when I feel like to (too bad no one leave comments here :( ). It is beneficial to see how others think about the course so that I can be sure I am on the same page as well. What's more, some of the slogs are just so interesting that they give me a lot of inspiration. For example, this slog includes a lot of discussion beyond the material that was taught in class. Reading this blog, I was also encouraged to search for more applications about recursion and linked list on my own. I have to say that blog as well as piazza are really good way to help students connect with each other in this course. Again, collaboration is important in the field of computer science. As a programmer, you want to stay up-to-date and surely you can't achieve this by yourself. My experience of keeping this slog has really made me believe that writing or keeping blogs encourage collaboration between students. I am sure you feel the same way as well : )

Last but not the least, writing slogs every week give me an opportunity to reflect on what I have achieved and what mistakes I have made. If you go over all of my posts here, you will find that I regularly post comments on quizzes, labs, assignments as well as tests. These are all great study materials for exam as I can refer back to what I find the most difficult to understand. At the same time, I tend to summarize my understanding of course materials in my weekly slog. Surprisingly, I find that doing this not only help me understand the concept better, but also help me remember them as well. As we are out of help from our TAs for the second part of this course, I do find slogging every week keep me updated about what is new in the class and continuously reflect on my study habits as well as the challenges I face.

Visiting other sloggers, I do find someone has a similar feeling as me in terms of keeping a blog, like this one. As I wrote in my first post, "every programmer should keep a journal or blog that records his or hers progress in programming. A journal can help you keep track of what you have done, what mistakes you have made and what you have learned from it. In this way, you ensure you understand the course materials and keep reflecting on failures or debugging processes. "  I think keeping this slog has definitely achieved this purpose, so that I would state it again that I agree with my earlier self, Geeks should WRITE!!!




Saturday, March 21, 2015

Test Cases and Assertion

Hello sloggers!! This week we talked about unit tests and assertion. In class, we went over the implementation idea for minimax and I am glad that we had a similar approach. One problem I encountered when I was trying to test on Assignment2 is that, no matter how many times I try playing the game, I still feel uncertain about my algorithm. This week's lecture actually provided an answer to this problem, Danny explained how to choose the "right" test cases and the possibilities of getting them all right at the same time is extremely small. I am now confident about our minimax algorithm as it passes the test cases we discussed in class. One thing I forgot to mention in the previous post is how we had trouble dealing with lists as parameters passing between functions. This posed a dangerous and really serious problem, as any changes you make to one list affect all the others that have a same reference. We found the solution after hours of trying detect the problem and we used deepcopy to solve this problem. In lecture, Danny introduced another way to make a copy of list instead of using deepcopy, and it looks like this
L3 = [[item for item in r] for r in L1]
I find this really interesting, since if you just put one forloop for the inside list, you end up only protecting the elements in the inside list from changing. To protect the whole list, you have to do it like that.
Another new thing we learned is assertion. It is a tool that can be used to state what we know is true at a crucial point in the code or what we assumed is true at the start of a function or method.
The syntax is
assert «condition», «error_string»
So the meaning for this statement is, if condition fails,
 raise AssertionError(error_string)
I think these will definitely become handy as I am doing my last assignment. I have learned how to perform effective test cases and I will apply the knowledge to A3.

Saturday, March 14, 2015

Reflection about A2 & Test2

Hi sloggers!! Can't believe we already past 2/3 of this course ... and congratulation on finishing assignment 2 and test 2!! This week we had a test, so we did not learn much. I will just do a quick summary and talk about how I think of A2 and Test 2.
In class, we went back to BST and talk about how we can add and delete an element. It may seems like a simple task, but in order to make sure the datas are organized in the way we want, we got to do some extra work. Here is the algorithm for deleting a node.
you have to consider all the possible cases and I personally find number 5 hard to understand. Yet, if you think about this: you have a node that has two children and you want to delete it. Your replacement of that node should still make the tree a proper BST, which means all its left nodes must be less that the replacement node. Therefore, you have to either replace it with the largest from the left or the smallest from the right. It looks complicated, but it actually make sense if you think about the problem in a logical way.

Assignment 2 is definitely harder than the first one. The process of tackling recursion is like you feel like you get the answer, but after a while it does not make sense to you any more. However, once you get it, then you actually get it. I am so glad that Danny was willing to stay for almost 1.5 hour after Wednesday's class at night. I also really enjoy discussing the problem with my teammates, even though rough_outcome surprisingly gave us a hard time after we finished minimax, we were able to finish it at time. I hope the strike can end soon so we can get our results back!
Test 2 is fair in generally, I am glad that I reviewed the lab problems on my own and put them on the cheat sheet (they're really handy>>>)
That is all I want to say. Hope you all have a great week!!!

Sunday, March 8, 2015

Link Them Together - Impression of Linked Lists

Hi sloggers, it is a new week again. Something unfortunate happened this week and I am sure you all must know about this, the strike. Sadly, I lost all of my tutorials but also got 4 hours of extra spare time every week. I hope that school can settle this properly as soon as possible. Tutorials are always beneficial as they offer practices for what I learned in class and my TAs are all really nice and good at explaining concepts. Anyways, I will try to keep up with my studies so let's talk about the new data structure we learned, Linked List!

A linked list is a sequence of nodes, each of which contains a value and a reference to the next node.
We used LLNode to represent a single node and LinkedList to represent linked list, which we call the wrapper class. Well, questions has been raised about why do we need this wrapper class. The answer is we want to know where does the list start and where does it end. otherwise, the data structure would not make any sense. 
Here is how you can think of a linked list in visual. Each box represents a LLNode

The __init__method of a LLNode class
Notice that self.nxt is None iff we are at the end of list.



we keep a reference to the front/head of the sequence. The back of the sequence is called the tail. 








traversing a linked list poses a little bit trouble as we can't access each node directly as in a normal list. Thus, we need to "walk through" a linked list and the general pattern is like this. 



We want to be able to perform normal operations like adding and deleting on a linked list. However, you gotta be extremely careful cause sometimes we may go so far in our "walk" that we lost the reference to go back one more step to make the changes we want.  The solution is to walk 2 references along the list, with one trailing behind a step.
There are a lot of practices in this week's lab, but I found them challenging as I went through them to prepare for next week's test. So, I discussed them with my friends and compared answer with the one Danny posted on course website. Here, I want to include one example and discuss some of the key points that I think deserve attention.
The key to any linked list problem is to DRAW PICTURES!! They are extremely handy in terms of understanding the whole process.              


To start, suppose we have a linked list like this 


Say we want to insert a node before A. We need to first walk through the list to find node A, then change the reference of E to refer to the new node  and link the new node to node A. Clearly, we need 2 references as we are walking through the list, since we want to access E after we find A. 

The picture looks like this. This is the general case and let's first write code up to the point we find node A.


This looks straight forward, but before we proceed, we still need to consider some special cases. 1. what if v2 is not in the list? then after the search for v2, cur_node would be None. 2. what if v2 is the first in the list? then we technically did not go into the while loop, so prev_node is None. keep this in mind and we can generate the rest of the code.








This is not that bad right? Again the key is to draw the pictures. I still need to practice more since I sometimes overlook the special cases, which can cause a big problem. I actually want to do a comparison between list and linkedlist, since they simply perform the same sort of tasks. Yet, today we have enough to say so I may go back to this post to continue on this topic or I may just simply do it in a later post. Thanks for reading and good luck on test2!!!

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!!