164k views
4 votes
Write a recursive function, len, that accepts a parameter that holds a string value, and returns the number of characters in the string. The length of the string is: 0 if the string is empy ("") 1 more than the length of the string beyond the first character

1 Answer

3 votes

Answer:

following are the method definition to this question:

def len(x): #defining a method

if(x==""): #defining condition that checks value store nothing

return 0# return value

else: # else block

return 1+len(x[1:]) #use recursive function and return value

print(len('The collection of table')) #call method and prints its value

Output:

23

Explanation:

In the above method definition, a "len" method is declared, in which x variable accepts as its parameter, inside the method a condition block is used, which can be explained as follows:

  • In if block, we check the value is equal to null if this condition is true, it will return a value, that is 0.
  • In this condition is false, it will go to else block in this block, the recursive method is used, which calculates value length and return its value.
User Giles Bradshaw
by
4.6k points