This week, I will be revisiting my slog from week 7 which detailed the process of recursion. More importantly, I will be comparing my experience in learning recursion to that of my classmates in order to better understand where misunderstandings may arise.
We can take a simple example from the lab exercises:
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).
>>> b = BTNode(8)
>>> b = insert(b, 4)
>>> b = insert(b, 2)
>>> b = insert(b, 6)
>>> b = insert(b, 12)
>>> b = insert(b, 14)
>>> b = insert(b, 10)
>>> list_between(None, 0, 15)
[]
>>> list_between(b, 2, 3)
[2]
>>> L = list_between(b, 3, 11)
>>> L.sort()
>>> L
[4, 6, 8, 10]
'''
if node == None:
return []
else:
if node.data < start:
return list_between(node.right, start, end)
elif node.data > end:
return list_between(node.left, start, end)
elif (start <= node.data <= end):
return [node.data] + list_between(node.left, start, end) + list_between(node.right, start, end)
One of my own misunderstandings when creating this code was the base case (which goes to show how even the simplest of things may present problems). I did not understand that when recursing through node.right or node.left, that the new node to be considered could ever refer to a NoneType so my base case had a different condition that node == None.
One my classmates, instead, had difficulty in returning a proper list. Since this function requires the recursion to return a list, each return statement, whether in the if or else clause, must return the desired values surrounded by square brackets (return [node.data] and not return node.data). This error caused my friends code to fail since the outputs were not even the same type. In addition, my friend also believed (wrongly) that:
[] + [3] = [[], 3] instead of [3] which obviously would have created problems in the code.
Perhaps even more important is the fact that we were able to fill in the gaps in each other's understanding of the recursive process so we were able to effectively learn from one another's mistakes.
As a final note, it is very important to understand that the construction of the base cases is intimately tied to the class implementation of the object that undergoes the recursion. For example, node.right and node.left have default None arguments which means that in recursion, the node will eventually equal None. For trees, on the other hand, there are empty lists so the object itself will never become None but rather []. As such, it is paramount to understand not just how to recurse but also how to modify the recursion according to the object type.
Overall, I am looking forward to the last week of classes learning about efficiency before exams!
No comments:
Post a Comment