When I first began to write code, I didn't see the need for comments. It never occurred to me that someone else would read my code and wouldn't instantly understand what my variable 'b' meant. In addition I didn't realize that I would have to understand other people's code.
Once I made the realization that readability of code was über important, I began to comment like crazy. However this slowed me down and eventually turned me off the idea of commenting altogether. How I made up for this was creating extremely good variable names, such that just by reading the variables' name one could tell what it is and how it should be used.
Much like my first encounter with code, I have now been asked for the writing SLOG of week 11 to revisit and old post and see if I agree or disagree with my position. I now realize that my old posts are analogous to my original uncommented code that I began to write as a young programmer. Now I am tasked to dig through weirdly named posts in order to find something that I've since changed my mind on.
Much like uncommented code, the above mentioned search took way too much time but I eventually found a post that I published at the end of January. It was called First Impressions and chronicled my panicked execution of Assignment 1.
I chose to revisit this one because I have learned something since I wrote it 2 months ago. I learned that the best way to figure out code or an idea is to argue about it with people who are equally passionate. Since then I believe I have posted about a really late night when I concurred minimax. This would not have happened alone and I am very thankful that I have managed to surround myself with like-minded people.
Study groups are something that I've never really been into because I work best in my own thoughts, but to externalize complicated problems and talk them out (yell at each other) is honestly a refreshing way to deal with a problem. From now on all of my computer science work will not begin with premature coding but will begin with an argument with friends as we try to decide what the best way to deal with a problem is.
Thursday, 26 March 2015
Sunday, 15 March 2015
Inserting and Deleting my Day Dreams
Without access to TAs, computer science labs have become much more boring. I no longer have someone to joke about code with as I write it, or ask question after question to as I just can't seem to get a program to run. The TAs in CS tutorials are an anchor, and we get to choose how far we float away before we tug on the rope and they pull us back to logic and reason.
Not only have labs become boring, they have become harder. At first glance at lab08 i started day dreaming as I normally do when I approach any math/cs problem. I day dream different routes to complete the task, and then without skipping a beat I try to disprove myself in every way possible. As a maths student, this is how I have to think to create proofs and critique other theorems. Logic dictates all and I approach CS in the exact same way. I imagine all possible outcomes and then evaluate how to achieve it.
As I believed I was nearing a solution for insert, I came up against a wall. The fact that a node could be inserted in to many different parts of a binary search tree while maintaining it's properties. For example (I hope the formatting doesn't get screwy when I publish this post), the following tree:
10
|
----------------
8 12
is a Binary Search Tree. Now let me show two different possibilities for inserting the number 9 into the tree.
10
|
----------------
9 12
---------
8 None
Or we could have the following:
10
|
----------------
8 12
---------
None 9
Both of these trees are Binary Search Trees, and both are the result of inserting the number 9 into our original tree.
In addition to this confusing property. What if the node 9 already exists in the tree? Do I just do nothing since it is already there? Can I add it to the left OR right branch? Is there some prior protocol on inserting it to the left or right that serves some purpose I can't fathom at the time being.
This is what my daydreams have come to, a sort of skewed nightmare. So I wish the TAs were back so I could get mine to wake me up out of this nightmare and talk some sense into me.
Not only have labs become boring, they have become harder. At first glance at lab08 i started day dreaming as I normally do when I approach any math/cs problem. I day dream different routes to complete the task, and then without skipping a beat I try to disprove myself in every way possible. As a maths student, this is how I have to think to create proofs and critique other theorems. Logic dictates all and I approach CS in the exact same way. I imagine all possible outcomes and then evaluate how to achieve it.
As I believed I was nearing a solution for insert, I came up against a wall. The fact that a node could be inserted in to many different parts of a binary search tree while maintaining it's properties. For example (I hope the formatting doesn't get screwy when I publish this post), the following tree:
10
|
----------------
8 12
is a Binary Search Tree. Now let me show two different possibilities for inserting the number 9 into the tree.
10
|
----------------
9 12
---------
8 None
Or we could have the following:
10
|
----------------
8 12
---------
None 9
Both of these trees are Binary Search Trees, and both are the result of inserting the number 9 into our original tree.
In addition to this confusing property. What if the node 9 already exists in the tree? Do I just do nothing since it is already there? Can I add it to the left OR right branch? Is there some prior protocol on inserting it to the left or right that serves some purpose I can't fathom at the time being.
This is what my daydreams have come to, a sort of skewed nightmare. So I wish the TAs were back so I could get mine to wake me up out of this nightmare and talk some sense into me.
Thursday, 5 March 2015
Submit -> Now what?
I am very pleased to say that I have finally finished Assignment 2. This accomplishment would not have felt remotely as awesome if there was no struggle involved in the process. Being a Varsity Athlete helps me understand that there is no reward without struggle, medals and accolades are meaningless with the effort that brought you to that point.
The effort I expended on Assignment 2 was far greater than that with Assignment 1. Starting to work on it weeks before it was due allowed me time to thoroughly think through the implementation. I'm very glad that I gave myself this much time because just this morning, 12 hours before it's due, I finally figured out why pep8 wasn't running correctly. This was the easiest bug to fix by far, but it's nice to reflect on all the points when I stumbled in order to truly appreciate finishing this Assignment.
My first real problem was with my method is_tippy() which checks if a board has a tippy on it. Up until that point, I was coding tippy_game_state and tippy_move while referencing subtract_square_state and subtract_square_move. Having code to reference is fantastic because as long as you have an idea of what you want to happen, the format exists and helps you formulate exactly how you want to implement a certain idea. Then I reached the first big catch, how do you tell when the game is over?
Subtract Square is easy, if current_total == 0... ta da, game over. Or even if there are no more possible moves. Tippy on the other hand, it could be over in the first 4 moves, even on a 10x10 board. After realizing the middle square of a 3x3 had to be used for a Tippy I generalized this for an nxn board, only checking the interior squares and their surrounding 3x3 neighbours. I then wrote code checking for each of the 8 possibilities on that smaller 3x3 board.
What I had in the end was a humongous block of unreadable code, if you didn't write it, you wouldn't understand what it did. After a while of staring at it I realized there was a lot of room for optimization. Taking out a line here, adding an if statement there, it slowly but surely reduced the number of lines needed. This process took a couple days as each time I thought I was finished with it, I'd put the project aside and then look at it tomorrow, only to realize that I had overlooked something. Eventually I got it down to it's current state and am quite satisfied as I proved to myself mathematically that it's impossible to optimize any further.
Another choke point to this assignment was mentioned in an earlier post, recursively changing the game state. To summarize when you popped back up a level in the recursive tree, the game state was still like it was in the leaf, so it returned an empty list error since there were no more possible moves. For more details see my post titled 'A Late Night With Recursion'.
My most recent error was dealing with pep8. For the longest time I couldn't figure out why it wasn't working, so I posted on Piazza.com. This morning someone replied with a cryptic remark about apostrophes. Instead of giving up hope I looked back through old questions on Piazza and eventually found exactly what I was looking for, the same question I had just asked, but this time with a much easier to understand answer. In essence the line of code to ask pep8 to check a file contained a weird stylized quotation mark which wasn't read by Wing101. So I deleted them and replaced them with my own quotation marks, and pep8 ran as expected.
So finally, after a long and arduous process, Assignment 2 is complete. I wouldn't have done it any other way. Which leaves me wondering... what should I do next?
The effort I expended on Assignment 2 was far greater than that with Assignment 1. Starting to work on it weeks before it was due allowed me time to thoroughly think through the implementation. I'm very glad that I gave myself this much time because just this morning, 12 hours before it's due, I finally figured out why pep8 wasn't running correctly. This was the easiest bug to fix by far, but it's nice to reflect on all the points when I stumbled in order to truly appreciate finishing this Assignment.
My first real problem was with my method is_tippy() which checks if a board has a tippy on it. Up until that point, I was coding tippy_game_state and tippy_move while referencing subtract_square_state and subtract_square_move. Having code to reference is fantastic because as long as you have an idea of what you want to happen, the format exists and helps you formulate exactly how you want to implement a certain idea. Then I reached the first big catch, how do you tell when the game is over?
Subtract Square is easy, if current_total == 0... ta da, game over. Or even if there are no more possible moves. Tippy on the other hand, it could be over in the first 4 moves, even on a 10x10 board. After realizing the middle square of a 3x3 had to be used for a Tippy I generalized this for an nxn board, only checking the interior squares and their surrounding 3x3 neighbours. I then wrote code checking for each of the 8 possibilities on that smaller 3x3 board.
What I had in the end was a humongous block of unreadable code, if you didn't write it, you wouldn't understand what it did. After a while of staring at it I realized there was a lot of room for optimization. Taking out a line here, adding an if statement there, it slowly but surely reduced the number of lines needed. This process took a couple days as each time I thought I was finished with it, I'd put the project aside and then look at it tomorrow, only to realize that I had overlooked something. Eventually I got it down to it's current state and am quite satisfied as I proved to myself mathematically that it's impossible to optimize any further.
Another choke point to this assignment was mentioned in an earlier post, recursively changing the game state. To summarize when you popped back up a level in the recursive tree, the game state was still like it was in the leaf, so it returned an empty list error since there were no more possible moves. For more details see my post titled 'A Late Night With Recursion'.
My most recent error was dealing with pep8. For the longest time I couldn't figure out why it wasn't working, so I posted on Piazza.com. This morning someone replied with a cryptic remark about apostrophes. Instead of giving up hope I looked back through old questions on Piazza and eventually found exactly what I was looking for, the same question I had just asked, but this time with a much easier to understand answer. In essence the line of code to ask pep8 to check a file contained a weird stylized quotation mark which wasn't read by Wing101. So I deleted them and replaced them with my own quotation marks, and pep8 ran as expected.
So finally, after a long and arduous process, Assignment 2 is complete. I wouldn't have done it any other way. Which leaves me wondering... what should I do next?
Monday, 2 March 2015
How Should I Orient My Objects Today Oh Great Flow Chart?
Object Oriented Programming.
Or should I say 'Programming in a style that is consistent with objects being the most important thing in a class like structure'.
In a nutshell, Object Oriented Programming can take a very simple problem like coding the game Subtract Square and make it into many hundreds of lines of code with a smorgasbord of classes. Thus when faced with a simple task, but adjoined with the footnote to use Object Oriented Programming, causes a lot of sighs from the general crowd of computer programmers.
However the benefits of Object Oriented Programming are quite robust and necessary for doing anything remotely complex in a readable way. Readability of code is a necessity, both for the programmer and anyone attempting to figure out what the code actually does. Naming conventions are very important and the layout makes everything more obvious, but to program with classes and effectively use __str__ and the like well, turns good code into great code.
The isolation of specific tasks into distinct methods in an overarching Class that deals with a certain type of object not only allows a reader to figure out what each call does, but allows a programmer to easily write each function and test it with an appropriate docstring. The use of docstrings in methods of Classes is my favourite way to construct code.
My old computer science teacher from high school had a saying which has stuck with me to this very day. He called it prematurely coding, writing code before you knew exactly what you wanted to occur and how you wanted it to occur. With a class of grade 10 computer science students, prematurely coding was a regular occurrence. Knowing you needed to go through every item in a list, and writing a for loop that does that before even considering what you're going to do with each item, or what data structure is necessary to facilitate one's calculations.
After assigning anything, he'd always tell us to write it out, to make a diagram, to actually do the math that was behind it all. Many students didn't take his advice at all. Most would end up with unreadable dysfunctional code, and a lucky few would end up with unreadable, convoluted, slow but working code.
Those who chose to follow his advice would eventually figure out that each problem he assigned didn't have to be solved with brute force but there was an elegant solution that could be coded in less than 10 lines, or with two simple helper functions.
A very memorable example of this was a tricky assignment from the middle of the year. It was simple stated as follows:
"Given Point A, Point B and Point C on a cartesian 2-Dimensional plane, write a function that returns true iff Point D lies within the triangle ABC."
I've always found with math and computer science, the simplest put questions are some of the hardest to solve. This challenge turned out to be no easy task for those who began to prematurely code. They did their best to find the equation of each of the lines AB, BC and AC and then determine the position of Point D in relation to each line. After writing several hundred lines of confusing code, it turned out that none of them could actually get the correct output for my teacher's testing cases.
Conveniently we had a field trip planned for the week after this assignment was due and we traveled to the work place of my best friend's dad, who happened to design software. He worked for Side Effects Software Inc., the company responsible for writing Houdini, a 3D animation software which was used to generate the strings on the balloons in up, along with the process of transforming transformers... the list goes on and on.
The field trip was a lot of fun as we got to listen to various programmers talk about working in the industry. For example their fun policy of after a days work, if anyone breaks the code that they're collectively working on, they have to bring in donuts for everyone the next day. This rule was gleefully told to us by a programmer who purposefully broke the code each day and fixed it right before he left so no one else could figure out if their changes worked or not, thus increasing the amount of donuts people brought him.
The important part of the field trip was when our teacher prompted my friends dad to talk about points inside of triangles. He told us that figuring out if a point is inside a triangle is a very important part of 3D modelling because every surface is created by tiny tiny triangles.
In the end the solution took a very interesting look at the concept of being inside a triangle by dividing the shape up into three more triangles: ABD, ACD and BCD and comparing the sum of their areas to the area of ABC. If the areas are equal, then D is inside the triangle ABC. If the sum of the areas is large than the area of ABC then the point is outside of ABC. This neat geometry trick is obvious when drawn on paper, and requires a formula that is very mathematical in nature. Given three points in a two dimensional cartesian plane, what is the area of the triangle defined by those two points.
After figuring out the process, and getting our hands on the equation, writing the code to solve the given problem was easy and every finished it in a single class time.
At Side Effects Software Inc. they have a method in their code that checks if a point is in a triangle, since they use this so often. Their use of Object Oriented Programming allows for more elegant code that comes together in an overarching design.
In the end, I've grown to love Object Oriented Programming as it makes things elegant and make sense. Creating a good program design requires a lot of programming before even touching a keyboard, and I do this best with flow charts. The file game_view in Assignment 2 can be represented by quite a complicated flow chart, but one that makes a lot of sense in the order and how things are executed. Hence I always create a flow chart when designing a program so that I correctly program it in an Object Oriented way.
Or should I say 'Programming in a style that is consistent with objects being the most important thing in a class like structure'.
In a nutshell, Object Oriented Programming can take a very simple problem like coding the game Subtract Square and make it into many hundreds of lines of code with a smorgasbord of classes. Thus when faced with a simple task, but adjoined with the footnote to use Object Oriented Programming, causes a lot of sighs from the general crowd of computer programmers.
However the benefits of Object Oriented Programming are quite robust and necessary for doing anything remotely complex in a readable way. Readability of code is a necessity, both for the programmer and anyone attempting to figure out what the code actually does. Naming conventions are very important and the layout makes everything more obvious, but to program with classes and effectively use __str__ and the like well, turns good code into great code.
The isolation of specific tasks into distinct methods in an overarching Class that deals with a certain type of object not only allows a reader to figure out what each call does, but allows a programmer to easily write each function and test it with an appropriate docstring. The use of docstrings in methods of Classes is my favourite way to construct code.
My old computer science teacher from high school had a saying which has stuck with me to this very day. He called it prematurely coding, writing code before you knew exactly what you wanted to occur and how you wanted it to occur. With a class of grade 10 computer science students, prematurely coding was a regular occurrence. Knowing you needed to go through every item in a list, and writing a for loop that does that before even considering what you're going to do with each item, or what data structure is necessary to facilitate one's calculations.
After assigning anything, he'd always tell us to write it out, to make a diagram, to actually do the math that was behind it all. Many students didn't take his advice at all. Most would end up with unreadable dysfunctional code, and a lucky few would end up with unreadable, convoluted, slow but working code.
Those who chose to follow his advice would eventually figure out that each problem he assigned didn't have to be solved with brute force but there was an elegant solution that could be coded in less than 10 lines, or with two simple helper functions.
A very memorable example of this was a tricky assignment from the middle of the year. It was simple stated as follows:
"Given Point A, Point B and Point C on a cartesian 2-Dimensional plane, write a function that returns true iff Point D lies within the triangle ABC."
I've always found with math and computer science, the simplest put questions are some of the hardest to solve. This challenge turned out to be no easy task for those who began to prematurely code. They did their best to find the equation of each of the lines AB, BC and AC and then determine the position of Point D in relation to each line. After writing several hundred lines of confusing code, it turned out that none of them could actually get the correct output for my teacher's testing cases.
Conveniently we had a field trip planned for the week after this assignment was due and we traveled to the work place of my best friend's dad, who happened to design software. He worked for Side Effects Software Inc., the company responsible for writing Houdini, a 3D animation software which was used to generate the strings on the balloons in up, along with the process of transforming transformers... the list goes on and on.
The field trip was a lot of fun as we got to listen to various programmers talk about working in the industry. For example their fun policy of after a days work, if anyone breaks the code that they're collectively working on, they have to bring in donuts for everyone the next day. This rule was gleefully told to us by a programmer who purposefully broke the code each day and fixed it right before he left so no one else could figure out if their changes worked or not, thus increasing the amount of donuts people brought him.
The important part of the field trip was when our teacher prompted my friends dad to talk about points inside of triangles. He told us that figuring out if a point is inside a triangle is a very important part of 3D modelling because every surface is created by tiny tiny triangles.
In the end the solution took a very interesting look at the concept of being inside a triangle by dividing the shape up into three more triangles: ABD, ACD and BCD and comparing the sum of their areas to the area of ABC. If the areas are equal, then D is inside the triangle ABC. If the sum of the areas is large than the area of ABC then the point is outside of ABC. This neat geometry trick is obvious when drawn on paper, and requires a formula that is very mathematical in nature. Given three points in a two dimensional cartesian plane, what is the area of the triangle defined by those two points.
After figuring out the process, and getting our hands on the equation, writing the code to solve the given problem was easy and every finished it in a single class time.
At Side Effects Software Inc. they have a method in their code that checks if a point is in a triangle, since they use this so often. Their use of Object Oriented Programming allows for more elegant code that comes together in an overarching design.
In the end, I've grown to love Object Oriented Programming as it makes things elegant and make sense. Creating a good program design requires a lot of programming before even touching a keyboard, and I do this best with flow charts. The file game_view in Assignment 2 can be represented by quite a complicated flow chart, but one that makes a lot of sense in the order and how things are executed. Hence I always create a flow chart when designing a program so that I correctly program it in an Object Oriented way.
Why is Minimax called Minimax?
On my first read through of the assignment, I skimmed through the Minimax part and didn't stop to consider why Minimax is named as it is. I didn't put any thought into this as my first reaction to the assignment is to design both of the Tippy classes, state and move.
Once I had an up and running game of Tippy that works perfectly with my random strategy, I had to deal with the looming task of programming Minimax. My first instinct was to have my suggest_move method call the method Minimax on each of the new states after applying each possible move. Minimax would then recursively check each possible game state and return 1, 0 or -1 depending on whether it was a winning or losing position.
I had a lot of trouble with dealing with the 1s and negative 1s. I wasn't doing a good job of keeping track of which player I was dealing with or which player was next player of the state and kept on getting my 1s and -1s mixed up. I had a lot of tests that I'd run to check to make sure that my code returned -1 for a SubtractSquareState where there was 2 coins left, since thats a very obvious losing position. However the choosing the best move process I had a lot of trouble with.
My solution was to comment out all my existing code and write a new iteration of it but without any 1s or -1s. Instead I would assign each state a str, either 'p1' or 'p2' depending which player had the winning position. If neither player had a winning position, it would return 'tied', which acted the same way as 0.
For the first time my Minimax code worked! However there was an absence of 1s, 0s and -1s. I felt pretty good about it as it had passed the Tippy test, picking the centre spot on a 3X3 grid on the first turn. However I started talking about Minimax with another student that takes computer science during our mutual philosophy class and he told me all about why Minimax was called Minimax. It's an algorithm, a pretty famous one at that, that Maximizes your score while Minimizes your opponents. Thus the naming is pretty clever, and this algorithmic solution can be generalized to non-zero sum games. This made me reconsider my code which doesn't minimize or maximize, it just picks the state that the concerned player wins in.
In order to try and redo my code, I commented it out and rejigged my suggest_move to call on my new method Maximize, which then called on my second new function Minimize, which called on Maximize etc. I thought this approach could work until I began to actually code it. I realized that both of these functions had almost identical code, and could easily be made into a single function. However once I amalgamated the two of them I began to run into my previously mentioned problems. Only after painstakingly drawing out trees of states and noting which player is next_player and whom I should be concerned with did my algorithm finally take shape.
I'm glad that I finally figured out why this strategy was called Minimax, and that it definitely saved me some marks here and there for a quite unorthodox solution to this problem. In the end my Minimax code is nice and straight forward, I would even call it elegant in some places. Recursion really takes a lot of onus off of a lot of unnecessary computation.
For the first time my Minimax code worked! However there was an absence of 1s, 0s and -1s. I felt pretty good about it as it had passed the Tippy test, picking the centre spot on a 3X3 grid on the first turn. However I started talking about Minimax with another student that takes computer science during our mutual philosophy class and he told me all about why Minimax was called Minimax. It's an algorithm, a pretty famous one at that, that Maximizes your score while Minimizes your opponents. Thus the naming is pretty clever, and this algorithmic solution can be generalized to non-zero sum games. This made me reconsider my code which doesn't minimize or maximize, it just picks the state that the concerned player wins in.
In order to try and redo my code, I commented it out and rejigged my suggest_move to call on my new method Maximize, which then called on my second new function Minimize, which called on Maximize etc. I thought this approach could work until I began to actually code it. I realized that both of these functions had almost identical code, and could easily be made into a single function. However once I amalgamated the two of them I began to run into my previously mentioned problems. Only after painstakingly drawing out trees of states and noting which player is next_player and whom I should be concerned with did my algorithm finally take shape.
I'm glad that I finally figured out why this strategy was called Minimax, and that it definitely saved me some marks here and there for a quite unorthodox solution to this problem. In the end my Minimax code is nice and straight forward, I would even call it elegant in some places. Recursion really takes a lot of onus off of a lot of unnecessary computation.
A Late Night With Recursion
Recursion is a tricky beast to handle.
I ran into an interesting problem with my recursive Minimax while coding over the weekend. A bunch of friends of mine that also take CSC148 got together over food and started discussing Minimax and the ways of creating it. After a few minutes we all had a very good idea about how to implement it and went our separate ways to actually write the few lines of code to get it to work.
Later that night at an ungodly hour, our mutual Facebook Chat exploded with us all complaining about the same error. So we met up again in my room and proceeded to try to explain to the others why the errors were happening. When logic didn't work, we resorted to volume, until my don told us that it was 3am and we were way out of line.
Eventually we stripped as much code away from minimax until all it did was run through every game state, and the same error occurred. It only went down until it hit a leaf, and then returned a NoneType error. We were all perplex. After drawing out way too many diagrams explaining the situation, we realized that when the move was executed, it changed the original game state. So once the base-case was hit and it recursively bumped up to it's parent, instead of seeing the correct game state, the game state was one of a finished game. Thus there were no possible moves however it was inside a part of the code that was only reachable if there were possible moves. Thus a None move was returned, creating a GameState of None which effectively broke our code.
Finally after much pacing and frustration, we tried the built in Copy class in python. Every time we applied a move to the state, we'd actually apply it to copy.copy(state). This still didn't fix our problem and we went back to the drawing board. This was until my very quiet friend who had sat through this entire process piped up from the corner of the room, "have you tried deep copy yet?" We all looked at him as if he was clinically insane.
"What's a deep copy?"
"I literally have no idea, it looks complicated and stuff. But it could work?"
Hopefully my buddy entered copy.deep_copy(state) and proceeded to run out code that had become littered with print statements, used for the endless debugging we were stuck in. Nothing had changed. We decided we needed to unwind so we left our residence and began to make a trek to our local 24 hour restaurant to enjoy some much needed food and beverages. Half way there we got a phone call from our same quiet friend who had decided to stay behind. Instead of beginning the conversation normally, he immediately reamed us out from being idiots and explained that we mistyped the deep copy code. Apparently it is actually copy.deepcopy(state), and once run it fixed the very problem that we had been pulling our hair out because of.
Nothing needed to be said amongst my group of friends, we looked at each other and turned on our heel to return to our warm room after braving the cold for no good reason. Once back we all dispersed to various corners of my room in an effort to beat each other to write the code for a working Minimax first. This turned out to be very profitable but quite anticlimactic, since in order to prove one's code works... they had to run Minimax. Running minimax for the first time on untested code is quite a trying experience because it takes literally 8 minutes and if you got it wrong... sucks to suck.
Not surprisingly my quiet friend won, after taking much longer than anyone else to write the code, but actually getting it correct on his first time running it.
What we ended up learning the hard way is the copy.deepcopy(s) is a great friend to have while doing recursion on an object in another class that is modified at each level of the reclusive call.
Subscribe to:
Posts (Atom)