Sometime during a lab we were requested to write recursive functions. I found it really confusing to write in the beginning, but my parented was very helpful, and we were able to finish the lab. Overall, recursion was not too bad for me as soon as I understood how to trace it, I think.
def rec_len(L):
if isinstance(L, list):
acc = 0
for i in L:
if isinstance(i, list):
acc += rec_len(i)
else:
acc += 1
return acc
The code above, for example, is a simple example of recursion that is used to counted the number of nested lists in a list. It recursively calls rec_len so that it will eventually goes through all of the nested lists in the given list L.
No comments:
Post a Comment