Exploring the Power of Recursion : A Comprehensive Guide to Recursive Functions in Python

Exploring the Power of Recursion : A Comprehensive Guide to Recursive Functions in Python

The Secret Weapon to Solve Tricky Programming Puzzles like a Pro

In this article, we'll learn in-depth about recursive functions in Python programming and its use case.

Check out the previous comprehensive article on Python Functions titled: Efficiency and Reusability : Harnessing the Power of Functions in Python in this Python series.

Recursion

The ability of a concept to be able to depend on or call its previous self within itself (run back or return to itself). When a concept or procedure is defined in a way that relies on an earlier or more basic version of itself, this is known as recursion. This is another concise way of achieving a loop construct.

Properties of Recursion Function

  • Base case: An end-point event that generates a solution without using recursion. Define how to stop the recursion to avoid an infinite loop of the function calling itself.

  • Recursive step: a collection of guidelines that pushes all subsequent cases closer to the base case (to meet the condition where it will exit calling itself).

Recursion Function in Python

A recursion function is a function that is applied inside its definition while it is being defined with base case to stop infinite loops of calling itself from occurring. A recursive function is a construct that can call itself or other functions repeatedly.

Structure of a Recursive Function

The recursive function is defined the same way a custom function is defined in Python but in this case it defines a base case and calls the function name within itself continuously until it meets the base case (condition).

#function definition
def recursive_fn(number):
    # base case condition to stop the function from calling itself infinitely

    # recursive case condition to check on the base case


#function calling with argument
print(recursive_fn(3))

Examples of Recursion in Python

Here are a few snippets where the recursive function is applicable

  • Find the factorial of the number 3!

Multiplying all the integers that are less than or equal to a given number (3) in this example is known as a factorial.

3! (3*2*1 = 6)

def recursive_fn(number):
    # base case
    if number == 1:
        return 1

    # recursive case
    else:
        return (number * recursive_fn(number-1))


print(recursive_fn(3))

#6

The recursive_fn() function takes in an argument of value 3 when it is called (invoked).

The base case to check against to stop the function from calling itself continuously is when the number is equal to 1.

Since the argument is higher than 1 the base case is skipped which allows the function to call itself again (recursive case) with a value that pushes it closer to the base case value (1)

(3 * recursive_fn(3-1))

(2 * recursive_fn(2-1))

"""once it gets to 1 which is the base case it stops calling 
itself and return the outcome of the solution (3*2*1) = 6
"""
  • Fibonacci Sequence

The Fibonacci sequence is a sequence where each successive number is derived from the addition of the two numbers before it.

def fibonacci_fn(n):
    #the base case to terminate the recursive function is 
    #if n is less than or equal to 1 
    if n <= 1:
        return n
    else:
        #the calling it own function on the subsequent cases closer to the base case
        return fibonacci_fn(n - 1) + fibonacci_fn(n - 2)

#using the index position value for each value of 0 through to 4 
for val in range(5):
    print(fibonacci_fn(val))

0, 0 +1 =1, 1+1 = 2, 2+1 = 3 = 0,1,1,2,3 (Fibonacci sequence of 5)

  • Summation of numbers from 1 to n

To find the summation of numbers from 1 to any defined value of n. For example, if n is 5 this recursive function will perform 1+2+3+4+5 = 15

# Write a recursive function that will sum all numbers from 1 to n. 
def recursive_fn(number):
    # base case to check if the number is less than or equal to 1 to stop the function from calling itself indefinitely
    if number <= 1:
        return number
    # recursive case
    else:
        return (number + recursive_fn(number-1))


n = 5
print(f"Summation of numbers from 1 to {n} is: ", recursive_fn(n))

  • Recursive function to reverse a string
# Write a recursive function that reverse a word.
def recursive_fn(word):
    # base case to check if each character has been reversed to stop the function from calling itself indefinitely
    if len(word) == 0:
        return word
    else:
        # recursive case unti it meets the base case
        return recursive_fn(word[1:]) + word[0]

reverse_word = 'Radar'
print(f"The reverse of {reverse_word} is: ", recursive_fn(reverse_word))

  • Recursive function to check if a word is palindrome

A palindrome is a word, number, phrase, or other group of symbols that reads the same both forward and backward

# # Write a recursive function that reverse a word.
def is_word_palindrome(word):
# base case to check if each character has been reversed to stop the function from calling itself indefinitely
  if len(word) < 2:
    return True
  if word[0] != word[-1]:
    return False
  # recursive case until it meets any of the base case
  return is_word_palindrome(word[1:-1])

palindrome_word = "radar"
print(f"The word {palindrome_word} is a palindrome: ", is_word_palindrome(palindrome_word))

The use cases of Python recursive function are much and largely dependent on the choice of the programmer when developing applications.

Conclusion

A recursive function is a function that can call itself until it can't call itself based on the defined base case (condition). It makes the code cleaner and concise. Recursive functions sometimes can be complex to write and debug. Practicing the application of recursive function will make it more easy to comprehend.

If you're looking forward to developing applications in Python using the OOP (Object-oriented programming), the major concepts are simplified on my blog here.

Find this helpful or resourceful?? kindly share and feel free to use the comment section for questions, answers, and contributions.

💡
Follow me on Hashnode: Alemsbaja X: Alemsbaja | Youtube: Tech with Alemsbaja to stay updated on more articles

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!