Thursday, 26 February 2015

Abstract Data Types (ADT) Part 2: An Example - Queue

As promised, my second post about ADT will be an indepth analysis of and ADT covered in class. In my previous post, I talked about ADT as a specification manual of some sort for some general object. At the end, ADT allowed us to be modular. There are several very useful abstract datatypes we covered in class. In addition to some of the built-in types such as integers, lists, etc, we covered several other ways to store data: trees, queue, and stack.
For no good reason, I want to focus on queues. Queues are first in first out structures. It may have enqueue, dequeue, and is_empty. Think about queues in a store. You're waiting to get your icecream on a hot summer day. If you come first, you can get your icecream first. It doesn't matter to the icecream seller who exactly is in position 2. All that matters is that the queue isn't empty, and the next person who gets icecream. When that person gets the icecream, they are removed from the queue

So translating the icecream stand using the concept of queues we get something like the following: is_empty? Yes
is_empty? Yes
someone came, enqueue Jayce
someone came, enqueue Katarina
is_empty? No
dequeue... Jayce
serving Jayce icecream
someone came, enqueue Corki
still serving Jayce icecream
Jayce got icecream is_empty? No
dequeue ... Katarina
serving Katarina icecream
still serving Katarina icecream
Katarina got icecream
is_empty? No
dequeue ... Corki
serving Corki icecream
still serving Corki icecream
Corki got icecream
is_empty? Yes
is_empty? Yes
... and so forth.

This doesn't apply just in the context of an icecream stand. Of course any line in a store can be used, but it's more than just that.

A less physical example is when requests are processed in the computer. For example, the computer seems to run a lot of programs simultaneously. In actuality, these are processed by a queue. Say you need to do X, Y, Z "simultaneously". You can create the illusion of simultaneous action by doing X, Y, Z, X, Y, Z, ... so forth but changing between them really quickly. It's kind of similar to flashing bird and cage to create bird in cage. Rapidly switching between tasks can make it seem like they are occuring simultaneously. In the context of a queue, we can think of X, Y, Z as being part of the queue. dequeue X and do X at the end enqueue X and then dequeue Y... and so forth.

The same basic data structure can be applied to many different "specific" cases since it's an Abstract Data Type.



My lab 6 Work

My solution for the assignment is attached at the bottom. For this post, I wanted to provide a detailed illustration of how I tackle recursive problems with list_longest_path as example. Due to time issues (on my part), I will "draw" my logic rather than providing a good written explanation.
I ended up writing a bit more than I originally planned, but anyhow, hope it helps.
I particularly like the implementation where None is taken as a base case. Its conceptually simpler I think. It's kind of like saying min([...] +[0]), which says what are the minimum value in list X; if this value is negative, return 0. Anyhow, these tree exercise and assignment 2 I think has provided me some insight into what it means to be "recursible"... I hope to address this in next week's post (unfortunately this week I must finish writing about ADT... and I'm a little busy now).

Wednesday, 25 February 2015

Abstract Data Types (ADT) Part 1: The Concept

Last post, I talked in depth about OOP. More specifically, I talked about the modularity and inheritance which makes OOP powerful. For modularity, you need to have specifications for each of the parts.

For example, let's talk about building a computer (hardware wise). There are many components, but let's talk about the most important few: motherboard, CPU, GPU, and RAM. Computer is modular, due to the specific way in which they connect to each other. Each of their roles are defined and thus the motherboard knows how to interact with the RAM. There exists some interface. Due to this defined interface, many different RAM can connect to the same motherboard, even though the exact architecture and exactly how it is done may be different from RAM to RAM. For example, you know that it must have a particular pin dimension to connect to the motherboard. When given input X and the query Y, two different specific RAM must know that query and also provide the same answer for the other parts interfacing it to understand the output.

What does the general RAM not know? A lot of things of course are not defined, but one such is RAM speed. There are specific details that the motherboard does not care about. Once the detail matters to the motherboard, the detail must be specified at the interface level to maintain modularity. With RAM for example, this interface is given a name such as DDR2 or DDR3. This has information about which RAM can be used for certain CPU.

Let's shift gears a little and think about how this relates to ADT. The general RAM is like an ADT, while the ADT's subclasses (which should be instantiated) is like a specific RAM that can be bought like Desktop Momory Model F3-10600CL9S-4GBNT. All the tasks and the way it performs those tasks (and in this case also the way it interfaces with the hardware ie. the pin connections) is specified in that general RAM so that specific RAM can follow them. In this case, the motherboard or whatever is interacting with the RAM is the client. Notice how the client does not need to know how the memory works. Only the operations and the results of those matter.

I mentioned above that ADT's are like specifications for the interface. This is related also to inheritance in that the subclasses inheriting from ADTs in a sense are promising to follow these guidelines. It's like companies advertising their RAM as DDR3. I think of inheritance from ADT as being a claim to follow these specifications. X which inherited from Y is an instance of Y. Thinking about our RAM, the GBNT is an instance of RAM.

Modularity in general is very powerful. In the context of computers, the most obvious benefit as a consumer is easy upgrading and fixing. Your GPU isn't good enough to support the new game in high resolution... just change that. You don't need to buy a brand new computer. It's the same with programming. In class, we are making a two player game where one of them is a computer. By using a strategy class, we were able to "upgrade" from a random move chooser to a minimax strategy where the best move can be chosen.

For fixing, suppose your GPU got some electrical shock and doesn't work anymore. Same idea. You can just get a new GPU rather than spending more money on getting everything. Similarly for software development, you only need to debug and fix what's not working. You don't need to spend time and effort fixing everything.

In addition, parallel development is possible now. In the context of computers again, the CPU making companies do not need to know about how memory will be stored etc. As long as the two development teams agree to do things in a certain way (establish an interface), they can develop things separately. In the context of programming, it means many people can work on the project together.

I feel like I've rehashed a lot of the material from my previous post but with a better conceptual illustration. For a summary of some of the OOP terms and ideas, see my previous post.

For the next post, I want to provide an example of very famous ADT we covered in class.

Thursday, 12 February 2015

list.copy() how much does it copy?

So for my previous post, I mentioned that the list gets copied, so having multiple parents is not possible. But, what does list.copy() actually copy?
I initially thought that it copies everything and I originally thought that copy was a call existent in the object class equivalent to eval(repr(obj)). But according to the following... I was wrong:

In fact, when you try to call copy on user implemented object (I tried it on tree) that does not define copy themselves, you get an error.

Anyhow, this means I was wrong about my previous conclusion and to actually duplicate the Tree objects, you actually need to use "deep copy". I think the easiest way to implement this would be to use eval(repr(Obj)).

My lab 5 work

So my work on trees lab is given below. I tried to remove redundancy that could potentially arise when t.children is empty and I did not follow the instructions on the handout closely... I kind of have my own way of doing things, which was mostly based on intuition at first, but after today's lab, I think I kind of know what I am doing. Maybe for a future post, I will elaborate on my way of tackling recursive problems.
Additional exercises and one extra function from lecture is also included.

Wednesday, 11 February 2015

My thoughts on Trees

Trees are a type of graph where each node can only have one parent... at maximum. Since the node must be part of the tree, it must be connected to the tree... basically by being a child of another node. A consequence of this is that (for a finite tree) there must be exactly one node without a parent. It's called a node.

There are a few very interesting things about a tree.

First is that a tree is made up of many other trees, which are called subtrees. I previously posted a question about what problems lend themselves to being solved by recursion. The fact that trees are made of smaller trees makes it obvious that that problems involving trees are good for solving by recursion.

Another interesting thing kind of related to the above is that the root only needs direct access to its children. At the end though, it can figure everything about the tree. In a sense, the tree has emergent properties.

But more interesting I think is the fact that the child nodes are not "aware" of their parent. I'm not sure if this is just an implementation factor, but the child has no knowledge of the parent in the following implementation (partial) provided in course lectures copied here for easy viewing:

It is actually impossible for them to point to the same tree as shown below (since a copy is made). However, when such a graph (not really a tree anymore) is built, many of the recursive functions intended to act on it will work. Of course for some things like counting leaves, it will behave a bit strangely and behave like tree in Figure 2. And I think it could be easily accounted for by checking if they are the same object etc.
Figure 1
But the above (figure 1) is definitely different from the representation below (Figure 2). 
Figure 2
I wonder if figure 1 like structure has a name (more specific than a graph)? it's like a tree but it can have multiple parents or is it not special enough for a name...


EDIT: I was a little wrong about figure 1 being impossible in this implementation. see my follow up post

OOP Part2: OOP Notes

I hope to make this post a bit more note-like rather than exploratory and to provide a summary of the course in a fairly concise way. I don't normally read the text so most of the terms were googled... As the course progresses and new concepts mastered, hopefully this post will grow... Some key words are underlined.

A data type consists of both attributes and methods.
Object oriented language allows for a way to create custom data types and also a way to create instances of that custom data type.
Class is the definition of objects.

Encapsulation is a idea that attributes and associated methods are combined into some data type allowing the client to interact with the public interface without worrying about the details of is implementation. In class we learned about property function in Python which allows the Class to control how the client accesses or changes its attributes.

Inheritance is the act of deriving from another so that the inheriting class (child class) is obtaining methods and attributes from its parent class. Note that the child class is a type of the parent class. Rather than thinking about them as inheritance, I think subsets is a better way to describe it, eventhough child classes can be extended.

Polymorphism is the ability of related data types to respond to the same calls in data type specific ways. In class, we learned about using NotImplementedError on the parent class to implement this kind of behaviour. (but NotImplementedError is not the only way to achieve polymorphism. sometimes, parent class may be implemented, but overriden or extended)

Extending is the act of making a child class more specific. This can be done by adding attributes or methods not defined in the parent or by overriding parent behaviour (methods). For example, suppose parent does x. the child can do xy.

Overriding is the act of literally overriding parent behaviour. For example, suppose parent does x when x is called. The child can ignore that and just do y.


I found this post to be a good overview of some of the concepts covered in class. This person recaps how to approach the design of a class in a manner consistent with our lecture. A lot of other OOP posts were a good summary, but nanalelfe's post is interesting in that if you only know OOP, there's nothing to compare to and thus it cannot be truely understood. I would argue though that although Python is a OO language, Python we learn in csc108 is not.

Anyhow, if you feel like I've missed any important terms or made a mistake, feel free to leave a comment!

Monday, 9 February 2015

OOP Part 1: What is OOP?

Today's food for thought is Object Oriented Programming (OOP). Actually, this will be an organized summary of some OOP concepts for reference (and slog requirement...) rather than any interesting ideas.

Before OOP came along, I thought about a program as a series of commands. Each command does something. I want to handle some repeating task... make a loop. I want to do something in certain cases... use an if statement. But at the end, these are all part of a command. Next, we link several commands into a new master command. We call this a function... Here, we realize that only certain data can be passed on and that these data may be linked together... why not create an object that binds all the data (attributes) together and the functions that operate on it (methods). Now, we have OOP. I made a previous post about usefulness of OOP describing mostly in the context of going from a function to objects.

So... in essence, objects are just containers. It is there for human beings to process what is going on more easily. I want to emphasize that objects are just there for human beings and our inability to track many things simultaneously. As an example, take 5 dogs. I spread around their names and colors and age etc all over the place. that's 15 variables. I can't remember which dog was what. Now let's link all those attributes into one thing- an object- a Dog! I can remember 5 things :) Now, the program remembers for me which dog has what attribute. It also remembers how they bark (see previous post), etc.

Only after understanding that OOP is a form of organization method to boost our productivity that we can talk about how to design them. I have provided my method for OOP design in a previous post with assignment 1 as an example.

In the next post to follow, I will discuss the components and more about how to think about OOP in a more theoretical way.

EDIT: Here and in most of my other posts on OOP, I only talk about the positive effects, but greying student has pointed out some pitfalls of OOP. What do you get when you subdivide your code too much? I think this idea is somewhat in line with the "human aspect" I talk about here, but anyhow, I thought it was interesting to point out.

Saturday, 7 February 2015

My Work for Lab 4

I'm going to try to post my solutions to the lab exercises every week. I would welcome others to compare my solution to theirs and comment if you think my solution can be improved in any way (or any other constructive criticisms are welcome :) )

My Queue.py:
My queue_list:
That's all the work I have with me here now... starting lab 5, I will try to fetch all my previous work and post everything and also post my soln to lab 5. Also, when I have time, I'll try to add some explanations... Adding tasks to queue... queue overloaded :)

Thursday, 5 February 2015

Recursion Part 2: Spin off Idea?

In Recursion Part 1, I talked about one analogous recursive formulation in mathematics and the logic for using "simplified" tracing.
Here, I want to talk about my attempts to create a recursive function for the additional exercises. I took just the docstrings and thought about how to write it. The docstrings are given below:
From the docstring, I could guess that for the recursive structure: if recursive_case then base_case, the base_case should be False... but it was difficult to understand where the element comparison should be...

At the end, the solution that I reached was:
Here, all the provided test cases work... but it is obvious that it would fail for case nested_contains(2,2).
I personally think that this should be the correct response of the function considering an object as a list of depth 0, but I'm just trying to match the specification here... so... after consulting the TA's advice, I used a helper function that would call this structure:
This kind of got me to think of structures where function A calls B calls C calls A calls B and so forth. I haven't thought much about this problem yet, but it can obviously be used when you need some cyclic behavior until a certain point. A trivial example is given below:
A very useless thing but the number of function calls to A might be the solution to something like kola climbs 2 cm and then slips 1 cm every day; how many days does it take for the kola to travel to the top of a 100 cm tree.
Another possibility is to call something depending on what was called previously, but this is structured in such a way that the caller can be called in the "chain" of calls.

Recursion is really interesting, but thinking about it in this way makes it seem like just another function... with one caveat that it might "loop" infinitely.

Tuesday, 3 February 2015

Recursion Part 1: Understanding the Logic Behind Recursion and Tracing

Today's question is when recursion can be used. Is this technique applicable for all problems, or is there only a subset of problems in which this idea can be used? Of course we only use it in iterables in all our examples in class... but can we be more general? Also, when is it a good idea to use it out of all the cases where it can be used?

But for now, I want to talk about the logic behind recursion
Ennanarts, jesse, and many other sloggers have shown recursion in a pictorial way. As you go in one step, you find that same thing. This kind of understanding is best exemplified by fractals as described by our course-link.

So, I want to show a slightly different approach: recursive form of mathematical expressions.
A sequence can be written in explicit form:
x(n) = 2^n
or
it could be written in recursive form:
x(n) = 2*x(n-1), x(0) = 1

In recursive form, the next value in the sequence is formulated as a function of the previous value. This means that if we can find that previous value x(n-1), we can find this value x(n). So... you do this again and again starting from n... until you reach a certain point... the base case (or in this case n = 0). But what if I gave you x(2) = 4. What is x(3)? Is it neccessary to unravel and go to x(0)? This leads to a fundamental logic involved in the tracing of recursive functions. After you prove/show the behaviour of a "lower level" in this case n - 1, you can use that result. it's not neccessary to go to x(0).

That's just some rationale about the "simplified" tracing scheme of recursive functions and also about another angle at which recursive functions can be thought about.

Next post, I would like to share some recursive functions from last week's lab and another function structure (or a spin off) that I was thinking about.

PS. type recursion on Google... it's really fun