Recursion to me was fun. I had heard about recursion before but I had never been formally taught it nor had I seen an example. Personally, I think recursion was the most important and interesting topic we learned about. I had no idea that we could use a function in its own body. It's important when we have nested lists if we wish to do something with the elements of the list. For example, if we want to add up the elements of a nested list, we'd have to use recursion. It is important to have a base case in any recursive function so it can end somewhere. For example, if we wanted to create a function that finds the sum for a nested list, we can check if something is a list and if it is, then go through the list recursively but if it isn't, then just leave it. Then we can add up and return all the numbers using sum.
I think it's a really useful tool to have especially when there is no guarantee of what the parameter could be. For example, if we were required to find the max number from a list and we could be presented with a nested list, we would need to get the max of each list in that list. This is where recursion helps. It can save a lot of effort in complex cases where a step has to be repeated again and again to get the desired solution
The only instance where I had to work with recursion was in the labs. It was my first time implementing recursion. My favourite lab was the one for week 5. We had to work with stacks. We had to create a function that could pick apart a list and add each element to a stack. It seems easy if we were given a list with a depth of 0 but once we are given a list that had more lists inside, recursion became useful. Though recursion is useful, it is important to have a way to end the recursive loop or else it will keep on looping. In other words, it is important to have a base case.
When it came to recursion, it got a little tricky trying to understand it completely because you have to be aware of how many times the recursive call is made. It can get messy. To learn recursion better, looked at different function and ran recursive calls manually to try and figure out the outcome. Then I ran the function on python to check my answer.
The midterm this week also had recursion in it and it wasn't too difficult. It's like a puzzle, you have to go through everything in steps to figure out one by one to get the correct output.
No comments:
Post a Comment