Let’s understand what is the recursion in programming with reverse string in Python program

Recursion is a process by which a function calls itself directly or indirectly. The corresponding function is called as recursive function

When Should I use Recursion ?

Recursion is made for solving problems that can be broken down into smaller, repetitive problems. It is especially good for working on things that have many possible branches and are too complex for an iterative approach.

Let’s understand the uses of Recursion by simple string reverse function.

Our goal is to reverse the given string in Python. If you are not familiar with python slice then check out the below code first

s= 'mayank'
print(" Slice : {} , First Character: {}".format(s[1:],s[0]))

Output: 
 Slice : ayank , First Character: m

s[1:] string except the first character and s[0] return the first character.

In below function, a string argument to a recursive function to reverse the string. Conditions are
if the length equal to 0 then return the string
else
called the recursion function to slice the part of the string except the first character and concatenate the first character to the end of the sliced string.

Reverse String in Python

def reverse(s):
    if len(s) == 0:
        print("Return String: " + s)
        return s
    else:
        f = reverse(s[1:]) + s[0]
        print(" Slice : {} , First Character: {}".format(s[1:],s[0]))
        return f

print(reverse("mayank"))

Output:

 Slice :  , First Charcter: k
 Slice : k , First Charcter: n
 Slice : nk , First Charcter: a
 Slice : ank , First Charcter: y
 Slice : yank , First Charcter: a
 Slice : ayank , First Charcter: m
knayam

Reference:

https://betterprogramming.pub/when-to-loop-when-to-recurse-b786ad8977de

Related Article:

Reverse String in Python using Recursion
(Visited 683 times, 3 visits today)