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
def recursiveLength(testVariable) :# Base Caseif (testVariable == "") :return 0# Recursive Caseelse :return 1 + recursiveLength(testVariable[1:])# Driver CodetestVariable = "Educative"print (recursiveLength(testVariable))
Explanation
The base case for this solution will test for an empty string ""
. If the string is empty we return .
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 to it.
The recursive case is based on the paradigm that the length of the complete string is more than the length of the string after removing one element.
.
Let’s have a look at an illustration:
Let’s try our hands at another challenge.