Saturday, 25 April 2015

container vs recursion

I'm finding that in some of the past exam questions, they specifically request NOT to use container objects. In their hint... it says use recursion...
So the following is a rev(q) that reverses the items in queue q using std queue functions and NOT usnig other container objects. FYI, I made enqueue and dequeue return the queue object after modifying. This just allows stuff like q.enqueue().enqueue().dequeue()... stuff like that. Anyhow, using this example I want to talk about what I think about this kind of method.
I'm not sure what the point of this question is because surely I don't use container objects but in the process of using recursion I create new name spaces and in essence I create variables that store things. The name spaces are like container objects. the next question is more interesting. can rev(s) be defined for stack s with similar restrictions? I'm not sure. If you can use loops and variables you can definitely hack this to work. It is possible to do something like exec("a" + str(i) + "=...") to make an "array of variables". I remember when I first learned programming and got to for loops I was thinking it would be awesome if I can autogenerate series of variables which conceptually was somewhat like arrays. Anyways... using recursion like above it's not possible. This is interesting because it kind of hints at how queues and stacks are complementary. With queues, you need a stack structure to reverse and with stacks you need a queue structure. It queues work with recursion because the namespace/namespace recursive calling forms a stack.

tree traversal

in a past exam, we are asked to figure out a unique tree given preorder and inorder traversal. I have briefly touched upon tree permutations before, but I think this is a slightly different question that asks you to understand recursion in tree traversal.

Based on this particular question, I was thinking that given preorder and inorder traversal you can always recreate the unique tree. I don't have a formal proof but the following can probably dressed up into such.

just a reminder:
pre-order = self, pre-order(left subtree), pre-order(right subtree)
in-order = in-order(left subtree), self, in-order(right subtree)

or simply:
pre: self, left,  right
in  : left,  self, right

I can see that the term right should be the last items... so what ever is the matching is the right most  "deepest tree".
Next, I go 1 left from in-order that's the "self" which is the parent of the right most item. I find that in the pre-order. I find where this value is from the pre-order. This is the new "self" (parent of the right most item) on the pre so everything between this and right is to the left of this. Now, all the suff here are the left subtree of the tree from the perspective of the parent of the right most node (which may be none btw if there are no matching elements). I repeat this process.

Here, I "traverse" the nodes from right, parent, parent's left subtree. Kind of interesting.
Obviously you can do the same with post and in order. Logic should be the same.

I should add that probably the nodes must be identifiable to reconstruct the tree. ie. repeating values may make it impossible. The obvious example is if all the nodes have the same value. All visits will give the same result.

As for why pre and post order doesn't cut it is kind of intuitive
pre-  : self, left,   right
post- : left, right, self
There are only two "distinct" blocks. self and (left,right);  (but also think in terms of trees). You cannot resolve everything. You see self being on the outter most of both pre and post so you can get rid of those but once you only have left and right... they are identical. Easy counter example would be a two node situation with parent P and child C. P with left child C has the same traversal as P with right child C.

Friday, 24 April 2015

new interesting question

This question talks about what I previously talked about... That the Tree class we constructed does not necessarily lead to a tree. cycles are permitted in the implementation and the objective is to find out whether this is in fact a tree.

First, we need to realize that the node may still be part of a something Not a tree (ex. two things are pointing at it). But there is no way to know this from the node.

If you think about the tree rules - they can only be reached in one way. so you can never see the same node twice if you "traverse all the nodes once".

I think this is interesting because you can't use sets for nodes (mutable. hashing is not possible for mutable instances). Of course the easy way is to just use lists. But is there something that is immutable and representative of what I'm thinking of that I can substitute here? memory location. id values. Having two different nodes (ie. "A is B" is not true) is okay even if they have the same value (the value need not be unique). It's the object itself that must be different and I believe id captures this idea.

Anyhow, my soln:

Past Exams

I'm starting to study for my final exam now. I got an interview on Monday :) so excited and I'm having a hard time focusing on studying so to keep myself motivated, I decided to post my solutions. I don't think anyone is reading my blog (o_O) but if you dear reader find any mistakes, do mention.

So the question is to determine whether or not a binary tree is "complete". Quick google search suggested complete binary tree is one where all nodes if applicable have 2 children. So minimum height binary tree. In class, we briefly touched on being balanced. Interestingly, the problem requests that I recursion NOT be used (which I thought was really weird).

It was a fairly fun problem. I used some sort of queueing system. I don't think the efficiency is good and the definitely a lot of room for improvement... but I do restrict my time spent on each problem (like on tests) to around 20 min (excluding typing problem time and debugging after to "verify" my solution since we don't get answer sheet)....

The function is called is_complete(root) and takes a BTNode. I think at the end, the restriction made me think of tree traversal differently. Definitely an interesting problem. I think I will get a recursive version up too (in a while). nvm I'll just explain the recursive version (too lazy to actually code it).

For the recursive version, you can code height(root) which returns the maximum number of paths ("non-reversing") in the tree leading from root to leaf. You also recursively find height2, which is where the first None occurs (so return min on "pseudo leaf" where pseudo leaf is where at least one of the two childs is None). Compare the two... and return False if the difference is greater than 1 (2 or more). I'm sure there is a better way though since you are traversing some parts of the tree multiple times. But I think the basic idea is there.

There are other stuff on the following... which is just some soln to other problems.


big O question

I want to post an interesting run time problem.

One problem goes as such: Given a length n list of lists of k ints, what is the most straight-forward way to check whether a given list of length k is equivalent to at least one of the lists (where same here implies that the order is also the same)?

For example:
input = [1,2,3], [[2,3,1], [2, 3,1]]
would give output = False
input = [1,1,2], [[2,2,1], [1,1,2]]
would give output = True

This is a very straight forward question. I can just compare the list 1 with list i where i ranges from 2 to n.
For each of the list comparisons, there are n elements to compare and thus you get n comparisons...

at the end, this is n*k comparisons.
So approx. I would say n*k time scale.

I want to modify the question to make it more interesting. What if you didn't care about the order? Suggest an efficient algorithm to do the comparison and discuss its time scale.

For me, the first idea that came to mind was to order the two lists using an efficient method. That would take it klogk time to sort and now I just need to make k comparisons so for each of the n elements (and the input list)... making it (n+1)*k^2*logk

But we know that sorting often slows things down. For example, is it faster to sort first and then find x or just find x?
To just find x, you need to say is x in list A? k comparisons, is x2 in A, k-1 and so forth. I get k(k-1)(k-2)... n times. k! comparisons n times.
so I get n*k!
Which is less than sorting first.

Can I do better? At first I wasn't sure. But I thought... I am looking for thing many items. It struck me then that I might be able to do better. What if I only sort the given list and look for elements in the long list in the sorted given list? Now:
O(n,k) = O_sorting_given_list + n*O_finding_k_elements_in_sorted_list
O(n,k) = k*log(k) + n*log(k)
now... O(n,k) = (k+n)*k*log(k)
which is better.

Is there a better way? I can't see it but I guess it doesn't mean it doesn't exist. This would make a very interesting test question. One problem I think with this course was that we didn't get interesting/sufficiently challenging problem sets (particularly in the latter half of the course) and the solutions are not very readily available. Working solution doesn't mean it's a great one and I would love to see alternate solutions.

Sunday, 12 April 2015

Finding Subsets

I often use programming to solve problems and automate tasks. Recently, I wanted to solve some simple optimization problem. I decided to generate all possible subsets in a list.
When I was thinking about this problem, I saw recursion.
Say you have a list of length n.
You can ask what the list of subsets of list n-1 is and then add element x
take that list of sets and add the removed element to generate an added set.

For example, take a list of 3 elements (A, B, C)
remove A.
Find the subset of 2 elements (B, C)
you get ((B, C), (B), and (C))
now generate the added set (B, C, A), (B, A), (C, A)
You should return (B, C, A), (B, A), (C, A), (B, C), (B), and (C))

The base case is when there is one element (empty is not a subset in this definition).

So I implemented this and found it to be slow. It's not supprising though. In a set of n elements, there are a set of 2^n  - 1
Based on this, there are at least 2^n base cases to evaluate. 2^n grows very fast and the problem really grows quickly. 

For optimization, I think the best way is to think about whether a variant of pruning could work. Based on the problem at hand, if smaller set meets the cut, the larger set may but if smaller set does not meet the cut, larger set will not work. I don't have to construct larger sets if the smaller set does not satisfy the condition. Depending on the exact conditions (which are the variables), there may be only a small number of possibilities.I'll see if this speed up, but I will probably need some additional optimizations. 

I'm thinking of trying to take the "best" choice at every step with a hint of randomness by also trying a few random elements. I think it's a variation of the finding a global minimum type algorithm. From my understanding, one of the ways to find minimum is by following the gradient, which only finds (possibly) a local minimum. In these algorithms, where you start is very important since you might be trapped in a local minimum and cannot find the global minimum due to this trapping. One of the methods used in such problems is to start the problem in many different "starting values". So for example, if you had the following function, if you start at the right hand side, you're going to find a local minimum, while if you start at the left hand side, you will find the global minima. If you start 50 different values between -5 to +5 increments, probably you will find the global minima. In this method though, you will obviously need to compute 50 times... which will take 50x more time.

One of the issues with approximations is that you compromise accuracy... But it stays practical and feasible. That's what's needed in science. In nature, I'm more of a pure scientist (meaning that I just enjoy the science because it's interesting rather than the practical benefits that come from it). But after working on "real" projects, I've realized that the world doesn't want pure science. They want results that are profitable or in some way useful. At first I was a little disappointed because to me science is like art - it's about making brilliant logic or experimental design to probe the world. At the end though, I think I've gotten kind of used to this need for practicality. 

Monday, 6 April 2015

Final post?

Classes have ended and only the exam is left.
I'm not sure if I will maintain this blog after I finish this course. I really enjoyed this course and I must admit that I really enjoyed posting here.

I'm not convinced as to how much it has helped people do better in general in the course. In fact, I don't think it helped me do better in the course (ie. I think my mark would be the same none the less). Surely, it helped me explore ideas and learn more, but I think that is mostly because I  really enjoyed posting and I posted a lot since there was so many interesting ideas (and I actually have several more that I was thinking of posting...maybe I will continue to post...). It's difficult to say that many other people had similar outcomes just based on one person's experience. But, I do want to talk about how things went for me. One of the things that happened though is that writing a post was a substitute for studying. For me, this is better than nothing since I probably would not have studied weekly. However, due to my personal circumstances (it isn't my core course and I have "more important" commitments), I did have to limit my total weekly contribution for this course somewhat. I think this is where this weekly posting falls apart. Sometimes, I had to write some posts during lectures or labs and so forth. I spent some time that I could have used on say building test cases or completing the labs more thoroughly.

I'm wondering if self evaluation is really worth the time. I think that if people are short on time, it may be better to do lab exercises for example. The "research question" should not be whether writing a blog helps students do better. It should be whether writing a blog is more helpful than another activity such as having extra lab questions. I guess the interesting argument comes where you have to realize that doing the lab questions is helpful... which seems many people believe that they were based on some of the other people's posts.

Maybe the point of the weekly post isn't to make us learn more (which is I believe the instructor's reasoning at least on the surface). Maybe it is to obtain feedback from peers. So that you know how you are doing. One of the requirements of the posts is to read other people's post. Although some people write wonderful posts (I mentioned several great bloggers) that many claimed to have helped to reinforce their understanding of the course, is this better than say reading a textbook (some of them are written in textbook style...). Maybe reading other people's post just help you see where you are... but then there's a bit of echoing effect in such cases where I've read for example relief that they are not the only person not able to solve recursion easily. Of course some post the opposite and mention how some other blogger has things down but I've found it to be rare. I do think that it would be interesting to analyze self evaluation trends here. If people are echoing their inability to do something and feeling relieved then that's not a good direction for the weekly posts.

I think that where our weekly point stands strongest is to encourage us to read and write and to create a sense of community. In my experience the CS community is very good in that way. Stackoverflow posts are super helpful for example. Probably, maintaining a portfolio is a good way to demonstrate your knowledge so my guess is that a great blog really can demonstrate your ability. I would say that if this were the purpose, the post recommendations should be updated a little (so remove a bit of self reflection and provide more guides as to what the post should look like), but I think although it may not necessarily improve our "computer science skills/knowledge", it may help as a computer scientist in the future.

Anyhow, I think my comp sci journey might end here... I will try to keep it as a hobby but probably it will be more programming than comp sci for me. To those who are just beginning their journey, good luck!