In this week's lectures, we learned about recursion functions. From what I recall, recursion is calling the function itself within the function, creating a loop until a certain condition is satisfied. For me and most of my classmates, the most difficult part of this function coding and implementing the loop (recursion). I still find it quite strange how a method call return a value to itself to use that value. It's python's own version of "Inception".
What we know about recursion so far is that it is a style of coding used inside a method, calling itself over and over again until some condition is satisfied and a value is returned. An example coding of recursion is given below:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
Let's say n = 5.
If we take a look at the factorial method here, we can see that it calls itself again within its else statement. From there, it briefly forgets about the n value and will run again with a different n value. As long as n is constant greater than 1, the method it self will iterate over and over again, reducing the value of n each time it is called. Once n has reached the value of 0, the method will begin to return values starting at 1. Once it returns the value 1, the method will jump back to the second last recursion call. Here we will get a return value of 2 * 1, but again, this is a return value to the third last time that the recursive method was called. if you noticed the pattern, the return values will continue to multiply with one another until it reaches the very first time the recursion occurred which will return a value of 120.
In short, recursion will iterate itself over a number of times from the bottom to the top. We can say that the bottom is the very last time that the method will be recursive while the top is the very first.
No comments:
Post a Comment