Okay, so maybe I don't understand recursion as much as I thought. I mean, sure, I can trace it after it's been written and I can grasp when and the overall idea of how it needs to be used. However, I realized while doing assignment two that I'm not entirely sure how to implement it, after the base case.
I usually start off with the one or two simplest cases, or where I want the recursion to end essentially. Although, getting to the middle, and calling the function multiple times is sometimes really confusing. I found myself comparing recursion to the idea of a while loop a lot, where you have a condition for which you want the loop to stop and it keeps repeating itself until it gets to that condition.
I suppose more practice will give me a better idea of how to use recursion, in general.
Recursion is certainly tough at first. So far in the class, we've mainly used recursion to add nested values, i.e. to a particular nested depth n, or to check if every nested level matches a particular condition. In this way, our outputs so far have always been ints or bools, respectively.
ReplyDeleteWhen it comes to ints, we know that our base case will have to return some integer value, often 0. For the recursive case, we'll just add a particular value at every recursive level in order to account for all values.
In the case of boolean outputs, the all() function comes in handy. In many cases three if conditions will allow you to complete a recursive function with a boolean output. One will present a condition that returns True. Another will present a condition that returns False. The last one will contain a recursive function of all([recursive_function(x)...]). This allows us to accommodate for all nested depths.
Anyway, I hope this helps clarify recursion. If you have any questions, feel free to reply to this comment. I'll do my best to answer!