This week was all
about recursion. My problem with recursion is that I spend too much time
thinking about how to implement the recursive calls. I hope I can improve upon
my speed, as I need to think fast for the upcoming midterm. Speed has always
been my weakness. Both in high school and since coming to university, finishing
tests under a time constraint has been a struggle. But practise makes perfect,
and I will redeem myself!
I worked on the lab
exercises this week. I found it very easy to write the first base condition,
where it does not involve recursive calls. But the else block was confusing
because I did not know how to incorporate the recursive calls. I found myself
just writing the code like it was not recursive. I had the biggest difficulty
with the function, max_length. The problem for me was to find a way to
accumulate all the lengths of the sublists (if there was any) and return the
max. I kept getting an error saying that you cannot find the length of an int
and that was when I realized I had to make sure to find the length of the
element I am iterating over only if it is a list.
The examples from
the lectures have helped me a lot. I make sure to go over each example by
myself after the lectures and write them out on paper. This allows me to make
sure I understand what is going on. Moreover, tracing the code by writing them
out also helps a great deal in understanding each step. I was particularly
confused with the nested_contains function we went over in class because of the
way it used the any method. The solution worked out in class was:
return
any([nested_contains(x, value)
if isinstance(x, list) else x == value
for x in list_])
By tracing the code
using the given docstring examples, I was able to understand how this code
works. It iterates over each element in list_, as well as the elements of any
sublists. When the element is not a list, it checks to see if the element
equals the given value. If it does, it returns True. The any method then sees
that there is a True, so it also returns True. After understanding this
example, I felt a little more confident in my knowledge in recursion.
No comments:
Post a Comment