Solution Review: Length of a String

This review provides a detailed analysis of the solution to find the length of a string recursively.

We'll cover the following

Solution: Using Recursion

Press + to interact
def recursiveLength(testVariable) :
# Base Case
if (testVariable == "") :
return 0
# Recursive Case
else :
return 1 + recursiveLength(testVariable[1:])
# Driver Code
testVariable = "Educative"
print (recursiveLength(testVariable))

Explanation

The base case for this solution will test for an empty string "". If the string is empty we return 00.

Now, for the recursive case, we call another instance of the same function but remove the first element. Now when the child element returns the length, we add 11 to it.

The recursive case is based on the paradigm that the length of the complete string is 11 more than the length of the string after removing one element.

lengthofstringfromindexiton1=1+lengthofstringfromindexi1ton1length\:of\:string \: from \: index \: i \: to \: n-1 = 1 + length\:of\:string \: from \: index \: i - 1 \: to \: n-1.

Let’s have a look at an illustration:


Let’s try our hands at another challenge.