We've had a whole assignment and a term test on recursion, and this week's Slog topic is recursion, so here goes nothing:
Recursion is, put very simply, when a function calls itself within itself. In more detail, a recursive function has a base case and one or more else/elifs. A base case is what the function would return if the input given to it is already in the form it needs to be in or if it's already what should be returned. For example, if I wanted to find the sum of all the numbers of a list, I would need to make sure I were only adding ints or floats because I can't sum lists.
Consider:
def sum_list(L: list):
return sum([sum_list(x) if isinstance(x, list) else x for x in L])
If I did sum_list([1, [2, [3, 4], 5]]), it would add 1, but [2, [3, 4], 5] is a list, so it would then do sum_list([2, [3, 4], 5]. It would then add 2, but [3, 4] is a list, so it would do sum_list([3, 4]) and add 3 and 4. 5 is not a list, so it would add 5 instead of calling itself again. The grand total: 15.
Apparently I don't understand recursion at all because I didn't do very well on the midterm. I'm not too worried, though, because I can't honestly say I studied enough. I put way more effort into the MAT136 exam I had on the same day, worth 3 times as much as the CSC148 test. Hopefully with the help of more assignments and labs, I'll finally wrap my head around more complicated recursive functions.
No comments:
Post a Comment