I cannot believe that the course is over. It's been such a long journey. With my initial shaky understanding of a lot of concepts, to the TA strike, to the midterms and assignments, and now the end of the course! I would like to take this time to thank prof Heap, who I think is a fantastic lecturer, and is also a great help during his office hours, and all of the TAs who have helped me, in labs and outside of them. I would like to reflect on my tests, and the labs, as well as my progressive understanding of course content, and what I'm still confused about. The midterms didn't go so well for me. Not because I don't understand the material, but because I don't test well. I have done very well consistently on my assignments, but not my midterms. I got 60 on the first one, mainly due to the time constraint and careless syntax errors due to said time constraint. I really did understand the material, though. On the second midterm, I got 44%. I was shocked when I saw my mark; I really thought I had done much better than that! So, when I got it back, I was relieved to see that my atrocious mark wasn't due to my lack of understanding. On the first question, I needed clarification on what exactly they meant by "arity", and whether that was the number of children for each parent, or the maximum number for each parent. I have seen the definition go both ways, and wasn't sure. Since we didn't have TAs in the room, I couldn't ask, and I was deducted marks where I clearly understood the concept. For the second question, I traced over the diagram in the correct order, instead of writing down the values, because this is what we had done in class, and I guess I didn't read the question as thoroughly as I should have. Anyways, my work was completely correct based on what I'd done, and I should not have been penalized, and gotten 0 on that question. On the last question, I knew exactly what to do, and I'd written it out in the comments, but I was so rushed for time I started jumbling all my ideas, and it came out as one incoherent blurb. I'm going to redo that question, to make sure I actually understand it.
As far as the labs, I have done all of them, aside from the last two, because I've had a lot of work to do. I found the labs to be really helpful practice; I didn't do well on the lab quizzes. I was in the hospital 3 times during the course of our first 5 labs, and they were stressful for me, especially since I was ill. I should probably apply for special consideration. I understand recursion much better than I initially did, thankfully. A3 really helped with that. I'm going to re-do the labs that have to do with classes; I remember having trouble writing __init__ methods, and knowing what to put as parameters. We'll see if that's still the case. I'm still a bit shaky on the concept of O(n). I believe it has to do with the run-time of a function. I also find difficulty in how to know when a function is dependent on certain variables, and how the run-time is affected accordingly. I don't know if we did best and worse case run-times, but I found a really good table on line that kind of helped me understand big O a little more. The link is here: http://bigocheatsheet.com . I need to re-do all of the labs and past exams in order to practice for the final exam; I'll be doing this next week after my calculus exam. To wrap things up, I really felt like I learned a lot in this course, and I really enjoy programming. In the future, I want to do a comp sci minor; I hope that I get into the program! I'll keep working hard! Thank you for reading my blogs, and good luck to everyone!
Klara's SLOG
Monday, 6 April 2015
Assembling the Sub-calls of My Knowledge About Recursion: AKA, YAY! I learned Something.
For week 11, we were asked to revisit one of our previous posts. Since recursion is a large component of the course, and it is probably going to come up a lot in the future, I shall revisit my previous post about recursion. Initially, I mentioned that recursion occurs when a function "calls itself", and that the base case terminates the recursion. While I agree with these statements, my understanding of recursion at that point was very shallow, as we had just started to learn about it. While I agree with my earlier points, I would also like to add to them. I mentioned that recursion looks a lot more concise that using loops (i.e.. for loops). However, as I discovered in A3, recursion isn't always as simple as a single line list comprehension that does the job for you. To elaborate, in my previous post about recursion, I mentioned that I was having trouble with a recursive call in the form of a list comprehension: ie. 1 + max[some_function(x) for x in t.children]. The function that I was referring to was the height(t) function from lab05. It looks like this:
def height(t: Tree):
''' (Tree) -> int
Return 1 + the number of nodes in longest path in Tree t.
'''
if t.children == []:
return 1
else:
return 1 + max([height(x) for x in t.children])
The reason I was having difficulty is due to the fact that I didn't fully understand how the sub-calls get assembled, and where the base cases are combined with the results from the recursive calls. (When I wrote my original post about recursion) Now, I have a better understanding through countless hours of mental breakdowns and practice. Each recursive call goes into a sub-call, until the base case is reached. The results from each call are then propagated back up the tree and combined, in order to create one final, comprehensive result. Each time a recursive call goes into yet another sub call, that function call is "paused", until the result from the sub-call is returned. The computer knows exactly where the recursive call was on hold, and this is why it knows how to assemble everything correctly based on your code and your base-case. I had a really hard time understanding this, but I am more comfortable with it now. Now, back to my argument that recursion isn't always a simple one line expression, I will use A3 as an example. There was a function in A3 called branching_stats, that needed to be implemented for option B. I'm not going to post my code here, because there are people that may not have handed in the assignment yet due to extenuating circumstances (such as myself), but I will speak of it in a general sense. Branching_stats required you to return a dictionary of arity to number of nodes with that arity. I guess you could call it a "dictionarity". HA. HAHAHA. Sorry. Bad pun. Anyways, for this function, not only did I have to implement a recursive call and store it in a variable, that recursive call was in a for-loop. And there were other for loops and a bunch of if and else statements as well. So, this function uses recursion, but it also uses loops as well. At least, that's how I implemented it, vaguely.
Now, to compare my SLOG to other student's SLOGs, I will say this first: I did not see anyone else write about tail-call optimization. So, I'm proud of myself for that, and I definitely stand by what I said. I've chosen to compare my understanding of recursion to 3 other classmates' understanding. The first person I've compared with has the blog domain:
http://beyoncepadthaiismywarriorname.blogspot.ca
We have been partners for all 3 assignments, so I thought it would be interesting to see what we both initially thought of recursion, and how much we've progressed, since I know that we've both been struggling with it. So, I read her post about recursion, and it seems that her understanding was either worse than mine, or she didn't have much to say about recursion at that point. All she said about it was that recursion is when a function calls itself. This is true; I'll give her that! I know she has progressed her understanding from that as well, just like I have. She hasn't written this weeks post yet, so I don't know what she'll have to say about recursion now.
Okay, for the other two SLOGs I'm going to be talking about, I'm not going to lie. I picked them based on the fact that their URLs sounded cool and creative. But they also had insightful things to say that I thought were comparative to my knowledge.
I was happy to see that the blogger behind the following SLOG wrote posts as long as mine:
http://allthemontypythonjokes.blogspot.ca/search?updated-max=2015-03-09T10:13:00-07:00&max-results=7
This person didn't really describe what recursion was, but stated that he/she got better at it with practice in the labs. I felt the same way; the labs were really helpful for understanding recursion. And, he/she also stated that recursion seemed fairly simple, like I initially thought, until he/she realized that he/she would rue those words when the functions got more complicated. The exact same thing happened to me. The blogger also spoke about how tracing recursion helped with his/her understanding. I should have done this more, in retrospect, because I may have understood how sub-calls are assembled sooner. The blogger hasn't written this week's post yet either, so I can't see what his/her understanding is like now, in comparison to my own.
My final comparison is to the following blogger's posts about recursion:
http://gamer-born-programmer.blogspot.ca
Initially, he (I'm using "he" now for simplicity's sake) thought that recursion was very difficult, and had a bare minimum understanding of it. It seems like he had less of an understanding than me. However, he did mention that he had a hard time wrapping his head around how the function calls itself. I had trouble with this too. I understood the concept and how it worked, but I always got stuck on the thought, "What if my function doesn't work? How can it call itself? The function isn't even finished being written yet before it calls itself!" Now I understand this concept. Firstly, you have to trust yourself and assume you've written the function properly, and it returns what it's supposed to. I never trust myself, so I had a lot of trouble doing this. Secondly, even though the function looks like it's not done, it is. The base case stops the recursion and propagates the results back up the tree combinatorially, and the computer knows exactly where each claws paused, and executes it from there. So, in short, trust yourself. In A3, I trusted that my function did what it was supposed to and returned the correct type, so I could store it in a variable and use it later and assemble it with all of the other components returned by the recursive call. I'm staring to be more confident with myself! The blogger of this SLOG, in this week's post, mentions that he used recursion in A3, and he now has a much better grasp on it, which is similar to my experience as well!
That's all for this week- thanks for reading!
def height(t: Tree):
''' (Tree) -> int
Return 1 + the number of nodes in longest path in Tree t.
'''
if t.children == []:
return 1
else:
return 1 + max([height(x) for x in t.children])
The reason I was having difficulty is due to the fact that I didn't fully understand how the sub-calls get assembled, and where the base cases are combined with the results from the recursive calls. (When I wrote my original post about recursion) Now, I have a better understanding through countless hours of mental breakdowns and practice. Each recursive call goes into a sub-call, until the base case is reached. The results from each call are then propagated back up the tree and combined, in order to create one final, comprehensive result. Each time a recursive call goes into yet another sub call, that function call is "paused", until the result from the sub-call is returned. The computer knows exactly where the recursive call was on hold, and this is why it knows how to assemble everything correctly based on your code and your base-case. I had a really hard time understanding this, but I am more comfortable with it now. Now, back to my argument that recursion isn't always a simple one line expression, I will use A3 as an example. There was a function in A3 called branching_stats, that needed to be implemented for option B. I'm not going to post my code here, because there are people that may not have handed in the assignment yet due to extenuating circumstances (such as myself), but I will speak of it in a general sense. Branching_stats required you to return a dictionary of arity to number of nodes with that arity. I guess you could call it a "dictionarity". HA. HAHAHA. Sorry. Bad pun. Anyways, for this function, not only did I have to implement a recursive call and store it in a variable, that recursive call was in a for-loop. And there were other for loops and a bunch of if and else statements as well. So, this function uses recursion, but it also uses loops as well. At least, that's how I implemented it, vaguely.
Now, to compare my SLOG to other student's SLOGs, I will say this first: I did not see anyone else write about tail-call optimization. So, I'm proud of myself for that, and I definitely stand by what I said. I've chosen to compare my understanding of recursion to 3 other classmates' understanding. The first person I've compared with has the blog domain:
http://beyoncepadthaiismywarriorname.blogspot.ca
We have been partners for all 3 assignments, so I thought it would be interesting to see what we both initially thought of recursion, and how much we've progressed, since I know that we've both been struggling with it. So, I read her post about recursion, and it seems that her understanding was either worse than mine, or she didn't have much to say about recursion at that point. All she said about it was that recursion is when a function calls itself. This is true; I'll give her that! I know she has progressed her understanding from that as well, just like I have. She hasn't written this weeks post yet, so I don't know what she'll have to say about recursion now.
Okay, for the other two SLOGs I'm going to be talking about, I'm not going to lie. I picked them based on the fact that their URLs sounded cool and creative. But they also had insightful things to say that I thought were comparative to my knowledge.
I was happy to see that the blogger behind the following SLOG wrote posts as long as mine:
http://allthemontypythonjokes.blogspot.ca/search?updated-max=2015-03-09T10:13:00-07:00&max-results=7
This person didn't really describe what recursion was, but stated that he/she got better at it with practice in the labs. I felt the same way; the labs were really helpful for understanding recursion. And, he/she also stated that recursion seemed fairly simple, like I initially thought, until he/she realized that he/she would rue those words when the functions got more complicated. The exact same thing happened to me. The blogger also spoke about how tracing recursion helped with his/her understanding. I should have done this more, in retrospect, because I may have understood how sub-calls are assembled sooner. The blogger hasn't written this week's post yet either, so I can't see what his/her understanding is like now, in comparison to my own.
My final comparison is to the following blogger's posts about recursion:
http://gamer-born-programmer.blogspot.ca
Initially, he (I'm using "he" now for simplicity's sake) thought that recursion was very difficult, and had a bare minimum understanding of it. It seems like he had less of an understanding than me. However, he did mention that he had a hard time wrapping his head around how the function calls itself. I had trouble with this too. I understood the concept and how it worked, but I always got stuck on the thought, "What if my function doesn't work? How can it call itself? The function isn't even finished being written yet before it calls itself!" Now I understand this concept. Firstly, you have to trust yourself and assume you've written the function properly, and it returns what it's supposed to. I never trust myself, so I had a lot of trouble doing this. Secondly, even though the function looks like it's not done, it is. The base case stops the recursion and propagates the results back up the tree combinatorially, and the computer knows exactly where each claws paused, and executes it from there. So, in short, trust yourself. In A3, I trusted that my function did what it was supposed to and returned the correct type, so I could store it in a variable and use it later and assemble it with all of the other components returned by the recursive call. I'm staring to be more confident with myself! The blogger of this SLOG, in this week's post, mentions that he used recursion in A3, and he now has a much better grasp on it, which is similar to my experience as well!
That's all for this week- thanks for reading!
Sunday, 29 March 2015
Impressions of Week 9
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!
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!
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!
Monday, 16 February 2015
OOP Summary
We started learning some objected oriented programming in csc108, and have now expanded upon our knowledge of OOP in csc148. I have to admit that learning OOP concepts was no easy task; I've constantly been told that python is a difficult language to start learning about OOP. We have covered a wide range of concepts, and thy are as follows:
1. Classes
I really struggled to understand what a class was and how all of the pieces are put together in a class through methods, in order to create objects. I was working on Assignment 1, and realized that I couldn't proceed with the shaky understanding that I had. I asked my older brother for help, and he provided me with a great analogy. If we have class Car, for example, the cars are going to be our objects that we want to create. We need to put n number of parts in, specified by the __init__ method, which will be put together by the car factory, which is the constructor. The constructor puts the parts together according to the blueprint in the company safe-this is the class. Then, once everything is assembled according to specifications, a Car object is created. Essentially, a class is like a blueprint for creating objects! I did well on the csc108 OOP part of the exam, but I guess I had lost my understanding over the break. I was proactive, and I asked the right person for help, and now I understand it!
2.Inheritance
Surprisingly, I didn't struggle with inheritance. This was actually one of the easier concepts for me to grasp. We needed to use a lot of inheritance in Assignment 1, so I learned it on my own before we learned it in class. When using classes, there are two ways to relate them (that I know of): inheritance and composition. In composition, one class has an instance variable that holds a reference to another class' object. Inheritance is useful when you want to create an abstract class (the parent) and have the children inherit all of its methods, so that new methods can be added if need be later on. Parent and children classes can act in a few different ways: actions on the child create an action in the parent. For example, if you call a method that isn't explicitly defined in the child class, it will look to use it in the parent class. Actions on the child override those of a parent. A method can be overridden by giving it the same name as the parent, and adding any parameters that you want the child to have. Actions on the child can also extend the actions on a parent. In Assignment 1, we did a lot of overriding, because the general game state and strategy classes could not be implemented due to lack of specificity. Therefore, we needed to raise a NotImplementedError, and have child classes of specific games inherit from the general parent classes, in order to override the methods and create specific, functional ones.
3.Class Variables
A variable that is shared by all instances of a class, and defined within a class is called a class variable. However, they are defined outside of any class methods. For example :
class Butternubs(object):
i = 7
>>> Butternubs.i
7
b = Butternubs()
4.Instance Variables
Instance variables are defined inside a method and are part of the current instance of a class. An instance is the same thing as an object. For example, "17 is an instance of type int", is the same as saying, "17 is an int object". This was a very good dual definition that I found on stack overflow when I was trying to learn more about instance variables. Whenever you have self.something = thing, self is the instance, and something is the instance variable. I will explain this more when I talk about methods.
5. Methods
A method is essentially a function that is a member of a class; it takes a class instance as its first parameter. The difference between a method and a function, is that a method must be called on an instance. We have been creating our own methods, but there are also special methods that we have been dealing with. __str__, __repr__, __init__, and __eq__ are special methods that we have been utilizing a lot, especially in Assignment 1. The __init__ method basically represents a constructor. When you call Foo(), python creates an object and passes it to the first parameter of the __init__ method, which is self, by convention. I believe that __init__ can be excluded if we don't wish to initialize any class variables. The __eq__ method is pretty straight forward. It checks whether or not two objects are equivalent, based on the code that specifies exactly what makes two objects equivalent. For example, it the game state class of assignment 1, two games were equal if certain things about their game states were equal (i.e. whose turn, is the game over , etc.) I struggled with understanding the difference between __str__ and __repr__ for a long time, but I went online to find some resources, and also worked through the assignment, which helped me a lot. Basically, __str__ returns a string representation of what needs to be displayed to the user (the object). __repr__ returns a string representation of self that produces an equivalent object when evaluated in python. In our class Point from lecture, __repr__ and __str__ would output:
>>> p. __repr__()
Point(3.0, 4.0)
>>>p.__str__()
(3.0 , 4.0)
6.Objects
An object is an abstraction of data. If I remember correctly, all objects created in python are stored in the Heap. Objects have identities, types, and values. Basically, everything in python is an object. I am still unsure about one thing: is a class an object? I have been getting mixed answers, and am not sure why. I know that a class contains objects, but this a class can still be an object too, right? Any thoughts are welcome, and are greatly appreciated!
Wel, that's my summary of OOP. I'm sorry about the length; it's a very involved part of programming and I wanted to make sure I covered/understood everything. If anyone has anything to add or correct, please don't hesitate! I like to learn, and know when I've done something wrong!
1. Classes
I really struggled to understand what a class was and how all of the pieces are put together in a class through methods, in order to create objects. I was working on Assignment 1, and realized that I couldn't proceed with the shaky understanding that I had. I asked my older brother for help, and he provided me with a great analogy. If we have class Car, for example, the cars are going to be our objects that we want to create. We need to put n number of parts in, specified by the __init__ method, which will be put together by the car factory, which is the constructor. The constructor puts the parts together according to the blueprint in the company safe-this is the class. Then, once everything is assembled according to specifications, a Car object is created. Essentially, a class is like a blueprint for creating objects! I did well on the csc108 OOP part of the exam, but I guess I had lost my understanding over the break. I was proactive, and I asked the right person for help, and now I understand it!
2.Inheritance
Surprisingly, I didn't struggle with inheritance. This was actually one of the easier concepts for me to grasp. We needed to use a lot of inheritance in Assignment 1, so I learned it on my own before we learned it in class. When using classes, there are two ways to relate them (that I know of): inheritance and composition. In composition, one class has an instance variable that holds a reference to another class' object. Inheritance is useful when you want to create an abstract class (the parent) and have the children inherit all of its methods, so that new methods can be added if need be later on. Parent and children classes can act in a few different ways: actions on the child create an action in the parent. For example, if you call a method that isn't explicitly defined in the child class, it will look to use it in the parent class. Actions on the child override those of a parent. A method can be overridden by giving it the same name as the parent, and adding any parameters that you want the child to have. Actions on the child can also extend the actions on a parent. In Assignment 1, we did a lot of overriding, because the general game state and strategy classes could not be implemented due to lack of specificity. Therefore, we needed to raise a NotImplementedError, and have child classes of specific games inherit from the general parent classes, in order to override the methods and create specific, functional ones.
3.Class Variables
A variable that is shared by all instances of a class, and defined within a class is called a class variable. However, they are defined outside of any class methods. For example :
class Butternubs(object):
i = 7
>>> Butternubs.i
7
b = Butternubs()
>>> b.i # class variable is accessed as an instance
7
>>> b.i = 3 # assignment to the instance
>>> Butternubs. i # does not change the class variable
7
Instance variables are defined inside a method and are part of the current instance of a class. An instance is the same thing as an object. For example, "17 is an instance of type int", is the same as saying, "17 is an int object". This was a very good dual definition that I found on stack overflow when I was trying to learn more about instance variables. Whenever you have self.something = thing, self is the instance, and something is the instance variable. I will explain this more when I talk about methods.
5. Methods
A method is essentially a function that is a member of a class; it takes a class instance as its first parameter. The difference between a method and a function, is that a method must be called on an instance. We have been creating our own methods, but there are also special methods that we have been dealing with. __str__, __repr__, __init__, and __eq__ are special methods that we have been utilizing a lot, especially in Assignment 1. The __init__ method basically represents a constructor. When you call Foo(), python creates an object and passes it to the first parameter of the __init__ method, which is self, by convention. I believe that __init__ can be excluded if we don't wish to initialize any class variables. The __eq__ method is pretty straight forward. It checks whether or not two objects are equivalent, based on the code that specifies exactly what makes two objects equivalent. For example, it the game state class of assignment 1, two games were equal if certain things about their game states were equal (i.e. whose turn, is the game over , etc.) I struggled with understanding the difference between __str__ and __repr__ for a long time, but I went online to find some resources, and also worked through the assignment, which helped me a lot. Basically, __str__ returns a string representation of what needs to be displayed to the user (the object). __repr__ returns a string representation of self that produces an equivalent object when evaluated in python. In our class Point from lecture, __repr__ and __str__ would output:
>>> p. __repr__()
Point(3.0, 4.0)
>>>p.__str__()
(3.0 , 4.0)
6.Objects
An object is an abstraction of data. If I remember correctly, all objects created in python are stored in the Heap. Objects have identities, types, and values. Basically, everything in python is an object. I am still unsure about one thing: is a class an object? I have been getting mixed answers, and am not sure why. I know that a class contains objects, but this a class can still be an object too, right? Any thoughts are welcome, and are greatly appreciated!
Wel, that's my summary of OOP. I'm sorry about the length; it's a very involved part of programming and I wanted to make sure I covered/understood everything. If anyone has anything to add or correct, please don't hesitate! I like to learn, and know when I've done something wrong!
Subscribe to:
Posts (Atom)