This week, my Wednesday night lecture section didn't have class due to the midterm. Therefore, will discuss the difficulty I had leading up to the midterm, how I solved the problems, and what I thought about the midterm. I'm aware that the Monday lecture covered BSTs, and the insert method. I looked at that method in the lab, and remember finding it confusing. I mainly didn't understand the following lines of code, which happens to be the first few in the method:
def insert(node, data):
return_node = node
if not node:
return_node = BTNode(data)
I was working alone in the library, and ended up asking my friend, who is studying computer science, what exactly the purpose of this statement is. I understand that it's the base case, but I guess the syntax confused me for some reason. All it says, to my understanding now, is that if the node that is passed in is equal to None (ie. node = None), then create a new BTNode object that contains data (which is passed in as a parameter).
I was unsure why we were revisiting this in class, since it is from lab 6, but I suppose Danny didn't want to cover new material, and maybe some other people needed it to be cleared up.
When I was writing my cheat sheet, I wanted to make sure that I understood all the concepts instead of just mindlessly writing them down. I went through all of the labs again and revisited my understanding of things to make sure I hadn't missed any pertinent information. I went over Stacks and Queues, even though Danny said we wouldn't have to know them for the midterm.
I'll lump the following explanation and problem solving into the "Reacts" component of our marking scheme. Lab 5 was a challenge for me. That was the last lab I went to (along with all other students) before the strike. I remember sitting in the lab thinking, "what the heck is going on?" My understanding of recursion was very shaky at that point, and I really didn't understand how to write recursively. So, I took break after the lab and took a crack at it a couple days later. I worked through it with my friend, who is in computer science. He never told me how to write the methods, but only gave me hints about where I went wrong in my code, and I tried to fix it from there. Something finally clicked then; I understood why the base case was so important. A lot of recursive code in this lab looked the same. The base case was in place to stop it from recurring, under different conditions! I don't know why I didn't understand this before, but it all makes sense now. I wrote all of the methods in lab 5 really easily after that, except for the arity method. This one really stumped me. I went on piazza to see if anyone else knew. Someone posted a solution, but it wasn't correct; he/she threw an arbitrary number into the recursive call in order to have a quick-fix to the problem. I'll admit, it's tempting sometimes, but it only works in specific cases, because it's not logical at all. Originally my code just looked like this:
def arity(t):
if t.children == []:
return 0
else:
return max([arity(x) for x in t.children]
The recursive part didn't do what it was supposed to, and I was surprised. so, I tried to trouble shoot and look at what had gone wrong. I realized that t.children is a list, and if you take the max of just that list, you are not taking into account the number of children that a node has. So, I then changed the recursive line to: return max([arity(x) for x in t.children] + [len(t.children)]) . The code then worked perfectly! I submitted my explanation to piazza and corrected the version that the other person had uploaded, and it made more sense to everyone else as well, so I'm happy that I was able to contribute.
After lab 5, I was much more confident with recursion, and lab 6 didn't cause me any problems really. Lab 7 was also pretty straight forward, and I discussed the difficulty I had with it in my last SLOG. So, all I have left is to briefly talk about the midterm. The midterm was fair, I thought. The problem I encountered with the first midterm was that it was marked really harshly with regards to syntax. I hope this doesn't happen again; I regret not submitting a re-mark request, because I clearly understood all the concepts, but was making silly mistakes like accidentally writing 2 ands or 2 ifs, or adding an s where the shouldn't have been one. These mistakes were all due to the time constraint, and nothing to do with my knowledge. Anyways, I thought the first three questions on the midterm were straight forward if you studied inorder, preorder, and postorder, and definitions. The second last question was difficult, but similar to what was in the lab, so I thought it was decent. In the last question, I was having difficulty knowing where to create new LinkedList objects and traverse the list, and I'm sure it was not completely syntactically correct because I was running out of time. I believe I wrote comments in order to clarify my ideas. I don't know how specifically I am allowed to talk about the midterm, but I'll leave it at that. That's all for this week. Thanks for reading!
Sunday, 29 March 2015
Saturday, 28 March 2015
Impressions of Week 8
In week 8, we focused on an entirely new concept: linked lists. These are different than the typical list type in python, which is represented by class List. In order to create a list object in python, one must simply use the class constructor, List(), in order to create an empty list. In csc108, and even in 148, we create lists by using the parentheses (ie. []). We can store the list in a variable, and can even choose to mutate the list if that is the intended purpose. Linked lists, however, are a specific type of list that inherit from the general List class. Each node in a linked list contains a reference to the next node in the linked list. The linked list can also be empty, of course. To link each node, they must contain a reference to each other. For example:
>>> node1 = Node(1)
>>> node 2 = Node(2)
>>> node1.nxt = node2
# node2 will have its nxt as None, and thus it is the end of the list. The nxt attribute was initialized in the __init__ method of the LinkedList class, and is not shown here.
Now that I've explained my understand of a linked list and the LinkedList class, I'd like to talk about the reading on linked lists, as well as methods in the lab that I found confusing, and methods that I had written differently than the posted solutions.
The __str__ method for linked lists in the assigned reading print values in a list without commas in between the list elements. I created my own __str__ method in order to practice recursion, as well as understand why wrappers and helpers are useful. Firstly, I created the wrapper, and realized I would need to create a helper afterwards. Here is the code:
Helper :
def str_rec(self):
return str(self.data) + ', ' + str_rec(self.nxt)
Wrapper:
def __str__(self):
return '[' + str_rec(self) + ']'
#it seems as though my __str__ method will still print an extra comma at the end; I have not shown how to get rid of it, but I believe that I could index into the list and remove it.
With regards to the lab, the _set_item(self, index, value) method took me a long time to write, specifically the last few lines of code. The method is supposed to set the current vale at the specified index to the value the user passes in as a parameter. Here is the code I came up with:
if index < 0:
index = index + self.size
if index > self.size or index < 0:
raise Exception('index out of range')
elif index == 0:
self.front.value = value
elif index == self.size - 1:
self.back.value = value
else:
search_node = self.front
for i in range(0, index):
search_node = search_node.nxt
search_node.value = value
To address the reacts component of our grade, I will focus on the "else" block. I had no trouble with the base cases, but I didn't understand how to search through the linked list. I looked online, but nothing was very helpful. Finally, I realized I should think of it in a less computer science specific way. How do you change something at a specific place? You find it, and you change the value. Simple! We've indexed into lists and changed the value at that index (mutation) so many times before. Linked lists are no different; you just have to be careful not to leave any node disconnected from the rest of the nodes in the list when you're replacing values. Therefore, I created a search node that would assure that it would be the one pointing to the next node in the list, and not the actual current node. Then, I found the index I was looking for, and replaced the cargo at that node with the specified value. Initially, I had trouble understanding why I needed this "search_node"; then, I drew myself a picture with arrows pointing to new locations, and everything made sense.
Finally, I was pretty proud of myself for getting a piece of code right one my first try; not a huge accomplishment for many people probably, but it was one for me! When writing the __add__(self) method, the docstring specified that the method's purpose was to concatenate two linked lists, and that we were not to mutate the original list. I then thought, "okay, I can created two new LinkedList() objects, and append values from the originals to the new ones." This is what the posted solution was; I wanted to try something different. My code even ended up being shorter in the end! Here is the code:
def __add__(self, other):
LL1 = copy.deepcopy(self)
LL2 = copy.deepcopy(other)
LL1.back.nxt = LL2.front
LL1.back = LL2.back
return LL1
By deep copying the originals, anything that is done to the copies does not modify the originals. The, LL1's back's next (which originally pointed to none), now points to LL2's front. LL1's back is now LL2's back, because they are part of the same linked list now. LL1 is returned because LL1's node.front is the head of the list, so every subsequent node in the list is linked through LL1.front.
Thank you for reading my SLOG! I know it was lengthy; I just wanted to make sure that I covered everything. If anything is incorrect, please let me know!
>>> node1 = Node(1)
>>> node 2 = Node(2)
>>> node1.nxt = node2
# node2 will have its nxt as None, and thus it is the end of the list. The nxt attribute was initialized in the __init__ method of the LinkedList class, and is not shown here.
Now that I've explained my understand of a linked list and the LinkedList class, I'd like to talk about the reading on linked lists, as well as methods in the lab that I found confusing, and methods that I had written differently than the posted solutions.
The __str__ method for linked lists in the assigned reading print values in a list without commas in between the list elements. I created my own __str__ method in order to practice recursion, as well as understand why wrappers and helpers are useful. Firstly, I created the wrapper, and realized I would need to create a helper afterwards. Here is the code:
Helper :
def str_rec(self):
return str(self.data) + ', ' + str_rec(self.nxt)
Wrapper:
def __str__(self):
return '[' + str_rec(self) + ']'
#it seems as though my __str__ method will still print an extra comma at the end; I have not shown how to get rid of it, but I believe that I could index into the list and remove it.
With regards to the lab, the _set_item(self, index, value) method took me a long time to write, specifically the last few lines of code. The method is supposed to set the current vale at the specified index to the value the user passes in as a parameter. Here is the code I came up with:
if index < 0:
index = index + self.size
if index > self.size or index < 0:
raise Exception('index out of range')
elif index == 0:
self.front.value = value
elif index == self.size - 1:
self.back.value = value
else:
search_node = self.front
for i in range(0, index):
search_node = search_node.nxt
search_node.value = value
To address the reacts component of our grade, I will focus on the "else" block. I had no trouble with the base cases, but I didn't understand how to search through the linked list. I looked online, but nothing was very helpful. Finally, I realized I should think of it in a less computer science specific way. How do you change something at a specific place? You find it, and you change the value. Simple! We've indexed into lists and changed the value at that index (mutation) so many times before. Linked lists are no different; you just have to be careful not to leave any node disconnected from the rest of the nodes in the list when you're replacing values. Therefore, I created a search node that would assure that it would be the one pointing to the next node in the list, and not the actual current node. Then, I found the index I was looking for, and replaced the cargo at that node with the specified value. Initially, I had trouble understanding why I needed this "search_node"; then, I drew myself a picture with arrows pointing to new locations, and everything made sense.
Finally, I was pretty proud of myself for getting a piece of code right one my first try; not a huge accomplishment for many people probably, but it was one for me! When writing the __add__(self) method, the docstring specified that the method's purpose was to concatenate two linked lists, and that we were not to mutate the original list. I then thought, "okay, I can created two new LinkedList() objects, and append values from the originals to the new ones." This is what the posted solution was; I wanted to try something different. My code even ended up being shorter in the end! Here is the code:
def __add__(self, other):
LL1 = copy.deepcopy(self)
LL2 = copy.deepcopy(other)
LL1.back.nxt = LL2.front
LL1.back = LL2.back
return LL1
By deep copying the originals, anything that is done to the copies does not modify the originals. The, LL1's back's next (which originally pointed to none), now points to LL2's front. LL1's back is now LL2's back, because they are part of the same linked list now. LL1 is returned because LL1's node.front is the head of the list, so every subsequent node in the list is linked through LL1.front.
Thank you for reading my SLOG! I know it was lengthy; I just wanted to make sure that I covered everything. If anything is incorrect, please let me know!
Sunday, 22 March 2015
Summary of Week 7
So, in week 7, a lot of stuff was happening. Prof. Heap was discussing A2 in class because the assignment instructions were almost too detailed to be understandable. (To me, anyways) It took a long time for my partner and me to implement minimax. I understood how it was supposed to work, and how the game theory worked and that the evaluation would be heuristic in nature if the run time were to be improved, but it was difficult to actually implement. It was necessary to have minimax play through a copied game state, and not the actual game. There were also issue with the .over method, in which an error kept occurring. Then, I was able to fix the problem by modifying apply move, in which it was necessary to do a deep copy of the board. I also found the starter code confusing at first, but I got used to it and it turned out to work very well with the rest of our methods' implementations. Hopefully the results of the assignment will be back soon, so I can see if our hard work payed off! Assignment 2 aside, we started working with Binary Trees. A binary tree is a specific type of tree ADT, where each node can have a maximum of two children. We also talked about Binary Search Trees; these are an even more specific type of Binary Tree. Everything in the right of the tree contains a greater value than the current node, and everything to the left contains a smaller value than the current node. Binary search trees are useful from an efficiency standpoint. For example, we did a lot of recursive exercises from the labs that asked us to return specific things from a binary search tree, such as a list of values of the children, or internal nodes, etc. Therefore, the search is efficient in the sense that you can recursively go through the left and right parts of the tree separately , and not go through any information that is not contained within the parameters of the method. (i.e.. if you want to find and return values in a certain range, you know exactly which part of the tree to recurse through) For example, this is my code for one of the methods in lab 6 (with part of the doctoring omitted for space conservation):
def list_between(node, start, end):
""" (BTNode, object, object) -> list
Return a Python list of all values in the binary search tree
rooted at node that are between start and end (inclusive).
>>> list_between(None, 0, 15)
[]
>>> list_between(b, 2, 3)
[2]
>>> L = list_between(b, 3, 11)
>>> L.sort()
>>> L
[4, 6, 8, 10]1
"""
if node is None:
return []
else:
return (list_between(node.left, start, end)
if node.data > start else []) + ([node.data]
if (start <= node.data <= end)
else []) + (list_between(node.right, start, end)
if node.data < end
else [])
I will admit that this function stumped me for a couple hours. I was confused as to how to go about it. But, then I realized that the base case was simple, and from there, all that needed to be done was to recurse through the left and right sides of the tree (using node.left and node.right, respectively), and then only include the nodes that are between the specified start and end. The syntax was difficult to grasp, and I still struggle with it when doing recursion, but it has been getting better through practice. We also touched on inorder, postorder, and preorder; they are very simple concepts to grasp, I find, but it's definitely interesting to draw a simple tree and trace out the order in which the nodes are visited. For inorder evaluation, you visit the left subtree first, then the node itself, then the right subtree. For preorder, you visit the node itself, then the left, then the right subtrees. And for postorder, you visits the left subtree, then the right, then the node itself. I think I am beginning to get a good grasp on binary trees, and I hope that my understand of recursion continues to get better!
def list_between(node, start, end):
""" (BTNode, object, object) -> list
Return a Python list of all values in the binary search tree
rooted at node that are between start and end (inclusive).
>>> list_between(None, 0, 15)
[]
>>> list_between(b, 2, 3)
[2]
>>> L = list_between(b, 3, 11)
>>> L.sort()
>>> L
[4, 6, 8, 10]1
"""
if node is None:
return []
else:
return (list_between(node.left, start, end)
if node.data > start else []) + ([node.data]
if (start <= node.data <= end)
else []) + (list_between(node.right, start, end)
if node.data < end
else [])
I will admit that this function stumped me for a couple hours. I was confused as to how to go about it. But, then I realized that the base case was simple, and from there, all that needed to be done was to recurse through the left and right sides of the tree (using node.left and node.right, respectively), and then only include the nodes that are between the specified start and end. The syntax was difficult to grasp, and I still struggle with it when doing recursion, but it has been getting better through practice. We also touched on inorder, postorder, and preorder; they are very simple concepts to grasp, I find, but it's definitely interesting to draw a simple tree and trace out the order in which the nodes are visited. For inorder evaluation, you visit the left subtree first, then the node itself, then the right subtree. For preorder, you visit the node itself, then the left, then the right subtrees. And for postorder, you visits the left subtree, then the right, then the node itself. I think I am beginning to get a good grasp on binary trees, and I hope that my understand of recursion continues to get better!
Monday, 2 March 2015
OOPs I did it again. Addition to my last post
Because the instructions for this week's SLOG ask that we choose a previous blog post to be marked, I would like to select my OOP post (the most recent one). One thing that I would like to point out is the highlighting of some of the points in white: I think this may be a mechanism for detecting plagiarism? In one of my paragraphs I cite that source that I obtained the example from, and in the other the definition of the class variable is mine. I'm sure it sounds similar to a lot of the definitions as to what a class variable is, which is why it is highlighted. I would also like to further reflect on my blog from last week by adding to it here, instead of editing the original post. So, if the paragraph below could be marked and included in my last post, that would be wonderful. I would like to add more of a "reaction" component, even though I did work some problem solving strategies and difficulties into my last post.
Reactions to learning OOP:
I mentioned that I didn't really understand what a class was and how I resolved that problem, as well as the fact that I tried to learn inheritance on my own in order to start the assignment. One thing that I was having trouble with is when to use "self". I had monumental amounts of trouble with it. Even though I knew that it refers to a particular instance, I somehow always added it where it was unnecessary. For example, on my midterm, I included "price" as a parameter in one of my methods, and wrote, "If self.price >= n..." etc. Why on earth did I do that? I thought I understood instances. I was rushing through the exam, so maybe it was an accident, but I felt that if I was really familiar with the concept, I would not have made that mistake. So, I went home and reviewed the exam, and tried to rewrite it without looking at the posted solutions. I also looked up some videos on OOP so that I could do the extra questions from the lab that I couldn't do beforehand. At least with this better understanding, I would have a starting point. I practiced writing __init__ methods continually, because I always had trouble knowing what exactly to include as parameters. As a general rule, I tend to store any information that will be necessary to create class objects and that will need to be used in other methods and subclasses. I also now know that if you declare something as a parameter, it doesn't need self in front of it, because whatever the user or developer is passing in for that parameter will get renamed to it, and it is therefore not an instance variable. I hope this explanation of my struggles is sufficient; I definitely feel that I have improved on a lot of concepts!
Reactions to learning OOP:
I mentioned that I didn't really understand what a class was and how I resolved that problem, as well as the fact that I tried to learn inheritance on my own in order to start the assignment. One thing that I was having trouble with is when to use "self". I had monumental amounts of trouble with it. Even though I knew that it refers to a particular instance, I somehow always added it where it was unnecessary. For example, on my midterm, I included "price" as a parameter in one of my methods, and wrote, "If self.price >= n..." etc. Why on earth did I do that? I thought I understood instances. I was rushing through the exam, so maybe it was an accident, but I felt that if I was really familiar with the concept, I would not have made that mistake. So, I went home and reviewed the exam, and tried to rewrite it without looking at the posted solutions. I also looked up some videos on OOP so that I could do the extra questions from the lab that I couldn't do beforehand. At least with this better understanding, I would have a starting point. I practiced writing __init__ methods continually, because I always had trouble knowing what exactly to include as parameters. As a general rule, I tend to store any information that will be necessary to create class objects and that will need to be used in other methods and subclasses. I also now know that if you declare something as a parameter, it doesn't need self in front of it, because whatever the user or developer is passing in for that parameter will get renamed to it, and it is therefore not an instance variable. I hope this explanation of my struggles is sufficient; I definitely feel that I have improved on a lot of concepts!
Subscribe to:
Posts (Atom)