Week 5: Object Oriented Programming
Building upon our understanding of object oriented programming and revisiting some previously covered concepts, week 5's material took a closer look at the implementation of classes and methods, particularly in the context of recursion in the tree structure - tree.py. Here, we first defined a number of functions including __contains__, leaf_count, and decendents_from_list, and eventually promoting each function to a method of the class object Tree.
I feel a couple of new items worthy of highlighting include:
a) copy(), a built-in function of python
b) the syntax and use of if and else in the examples of init and repr:
def __init__(self, value=None, children=None):
self.value = value
self.children = children.copy() if children else []
&
def __repr__(self):
return ('Tree({}, {})'.format(repr(self.value), repr(self.children))
if self.children
else 'Tree({})'.format(repr(self.value)))
Classically, we were taught that if and else should begin at the start of a statement, otherwise we would usually return some form of a syntax error. Here we see the exact opposite, and it works! It seems as though we're breaking more and more of these once arbitrarily defined rules. May be they were constructed as a way to help us understand the basics without having the confusion... Is it just me, or is python starting to feel more obscured?
I'm also beginning to appreciate the complexity of using an array of functions within functions or methods, rather. I shamefully admit that this took me way too much time to understand.
def descendents_from_list(t, L, arity):
q = Queue()
q.enqueue(t)
L = L.copy()
while not q.is_empty(): # unlikely to happen
new_t = q.dequeue()
for i in range(0,arity):
if len(L) == 0:
return t # our work here is done
else:
new_t_child = Tree(L.pop(0))
new_t.children.append(new_t_child)
q.enqueue(new_t_child)
return t
As an aside and a final note, assignment 2 was posted recently and for those trying to get a better grasp of minimax, I found a good resource to read up on: http://neverstopbuilding.com/minimax. Cheers.
No comments:
Post a Comment