Answer:
Here is the Python program:
def measure_string(myStr): #function that takes a string as parameter
if myStr == '': #if the string is empty (base case)
return 0 #return 0
else: #if string is not empty
return 1 + measure_string(myStr[0:-1]) #calls function recursively to find the length of the string (recursive case)
#in order to check the working of the above function the following statement is used
print(measure_string("13 characters")) #calls function and passes the string to it and print the output on the screen
Explanation:
The function works as following:
Suppose the string is 13 characters
myStr = "13 characters"
if myStr == '': this is the base case and this does not evaluate to true because myStr is not empty. This is basically the alternate of
if len(myStr) == 0: but we are not supposed to use len function here so we use if myStr == '' instead.
So the program control moves to the else part
return 1 + measure_string(myStr[0:-1]) this statement is a recursive call to the function measure_string.
myStr[0:-1] in the statement is a slice list that starts from the first character of the myStr string (at 0 index) to the last character of the string (-1 index)
This statement can also be written as:
return 1 + measure_string(myStr[1:])
or
return 1 + measure_string(myStr[:-1]) This statement start from 1st character and ends at last character
This statement keeps calling measure_string until the myStr is empty. The method gets each character using a slice and maintains a count by adding 1 each time this statement is returned.The function breaks string into its first character [0:] and all the rest characters [:-1]. and recursively counts the number of character occurrences and add 1. So there are 13 characters in the example string. So the output is:
13