According to dictionary.com, recursion is defined as the process of defining a function or calculating a number by the repeated application of an algorithm. In computer programming, recursion is most used as a problem solving technique when an algorithm is being repeated.
Using python's built-in functions aid to create a recursive function.
The general form of recursion is:
if (condition to detect a base case):
(do something without recursion)
else:
(do something that involves recursive call(s))
The first if case is when or how to stop the the function (the base case), and the else case specifies how to combine recursive subcalls.
simple example) Factorial is the result of multiplying a sequence of descending natural numbers.
5! = 5 * 4 * 3 * 2 * 1
Another way to look at this is:
5! = 5 * 4!
5! = 5 * 4 * 3!
and so on.
This is recursive!
The following example uses recursion to evaluate factorials.
def factorial(number):
if number <= 1: # base case
return 1
else: # in general
return number * factorial(number - 1)
Looking at the call:
>>> factorial(5)
Tracing:
We notice that 5 (number) is greater than 1. So, we move to the else condition.
So:
return 5 * factorial(5 - 1) -> 5 * factorial(4)
We notice that 4 (number) is still greater than 1. Se we move to the else condition.
So:
-> 5 * 4 * factorial(3)
and so on, until we get:
-> 5 * 4 * 3 * 2 * factorial(1)
Now, we see that 1 (number) is equal to 1, so we go to the first condition (the base case) and see that we return 1.
Thus:
-> 5 * 4 * 3 * 2 * 1
-> 120
Wow, nice explanation on recursion. Great work!
ReplyDeleteWow, nice explanation on recursion. Great work!
ReplyDelete