The Recursive Algorithm in Python

The Recursive Algorithm in Python

Hi guys, I created my Hashnode's account today, and I am really excited about the fact that I get to document my journey as a developer! So while going through a repository on GitHub, I found an algorithm I really wanted to know more about, the Recursive Algorithm.

What is a Recursive Algorithm

A recursive algorithm is an algorithm which calls itself with "smaller (or simpler)" input values, and which obtains the result for the current input by applying simple operations to the returned value for the smaller (or simpler) input.

In Python, you can implement the recursive algorithm by writing recursive functions.

What is a recursive function

A recursive function is a function that will continue to call itself and execute its code, until a certain condition is met.

When writing recursive functions, you should be very careful, in order to avoid writing codes that never terminate. Here is an infinite recursion I wrote while trying to come up with the factorial function code:

def factorial_of_a_number(number):
    # The base case:
    if number == 1:
        number = number * 1
        return number
    else:
        # The recursive case:
        number = number * (number - 1)
        factorial_of_a_number(number)
        return number

factorial = factorial_of_a_number(3)
print(factorial)

A recursive function is made up of two parts, the base case and the recursive case. The base case can also be called the termination condition, because when once its condition is met, the function stops. While the recursive case is the part of the program that tells the interpreter to keep calling the function.

Example

A recursive function to calculate the factorial of 6.

# The factorial of six(6!) is defined by:
#  6 * 5 * 4 * 3 * 2 * 1 = 720

def factorial_of_a_number(number):
    # The base case:
    if number == 1:
        return 1
    else:
        # The recursive case:
        return number * factorial_of_a_number(number - 1)


factorial = factorial_of_a_number(6)
print(factorial)

output:

720

Conclusion

Recursion doesn't need additional variables to be executed, it enables you breakdown complicated problems into smaller parts to enhance solving, and it allows you to write simple and concise programs, which is very Pythonic. It will be very easy for a programmer to write an infinite recursion, but then, "practice makes perfect."

References:

  1. Understanding recursive functions in Python

  2. Python thinking Recursively

  3. Recursion in Python

  4. Recursive Algorithm