A great example to practice both, loops and recursion, is to create a python program to calculate the factorial of a number.
The factorial of a number is defined as follows:
f(n) = n * f(n-1)
f(0)=f(1)=1
So, let’s start with the loop version of the program.
Python program to calculate the factorial of a number using loops
In programming, we call iterative functions those that are not recursive.
In our current example, we can use one of the 5 basic algorithms and modify it so we can solve the current problem.
If you look at the basic algorithm for summing, you will notice that we can use it, but instead of summing, we should multiply, according to the definition of factorial. The modification we need to do is to initialize the variable that will accumulate the results to 1.
The reason is that 1 is the neutral for the multiplication. If we initialize the variable in 0 and multiply, we will obtain 0 at the end.
See the code below.
def iterative_factorial(n):
f = 1
for i in range(2,n+1):
f = f * (i)
return f
Because we know 1 is neutral for multiplication, there is no reason to start the loop in 1. If we do so, the variable f won’t change its value.
Python program to calculate the factorial of a number using recursion
The factorial of a number is a classic example used in recursion.
Remember in recursion, we need to find the basic cases, this is when the recursion will finish. In this case, if n equals 0 or 1, we know that the factorial is 1. So this is when we will stop the recursion.
The second thing we need to do is to divide our problem into the same type of problem, but with a smaller instance size. That is if our original problem is to calculate the factorial of n, and we find a sub-problem, which is to find the factorial of n-1, the second one has a smaller instance size, n-1<n.
Lastly, we combine the partial solutions. In this case, the combination is to multiply n and the factorial of n-1.
See the code below.
def recursive_factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * recursive_factorial(n-1)
You can test the two implementations with the python console program below.
if __name__=='__main__':
n = int(input('Enter a number greater than 0: '))
print (recursive_factorial(n))
print (iterative_factorial(n))
H@ppy coding!
Related posts: