Sunday, 19 February 2017

Recursive program in python

Now we come to implement the factorial in Python. It's as easy and elegant as the mathematical definition.
 
 
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)
We can track how the function works by adding two print() function to the previous function definition:
def factorial(n):
    print("factorial has been called with n = " + str(n))
    if n == 1:
        return 1
    else:
        res = n * factorial(n-1)
        print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
        return res 

print(factorial(5))
 
 
 
This Python script outputs the following results:
factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for  2  * factorial( 1 ):  2
intermediate result for  3  * factorial( 2 ):  6
intermediate result for  4  * factorial( 3 ):  24
intermediate result for  5  * factorial( 4 ):  120
120




Let's have a look at an iterative version of the factorial function.
def iterative_factorial(n):
    result = 1
    for i in range(2,n+1):
        result *= i
    return result

No comments:

Post a Comment