Saturday, January 31, 2015

Recursion Hurts My Brain!

We learned about recursions in class this week and it took a while for my brain to understand the code.

Take the lab, for example.
Tracing the code was doable for me, but it took more and more brainpower as more and more sublists were added into lists.

Writing the code for length(L) was very confusing.
I started out with
if isinstance(L, list):
    return [length(x) for x in L]
else:
    return 0

My if statement started out by replacing each element in L, whether it was a list or a sublist, to 0's.
Then I had difficulty going into each sublist to find the length of each list and return the maximum length.

I knew I had to somehow incorporate max() and len() into the code...

When the list has one sublist inside the list, I'm comparing to the length of the outside list, and the length of the list inside.
But what if there was another sublist inside the sublist?

Then I would have to take the maximum of the first sublist and compare it to the length of the sublist inside the sublist.

Which means the if statement should be:
if isinstance(L, list):
    return max(len(L), max([length(x) for x in L]))





No comments:

Post a Comment