educative.io

Confusion regarding returning and calling

def countChar(str, char):

‘’’

you can call helper function as countChar_(str[1:], char)

‘’’

if len(str) <= 0:

return 0

if str[0] == char:

return 1 + countChar_(str[1:], char)

else:

countChar_(str[1:], char)

in the correct result, the last block of else was something different, it was returning countChar_(str[1:], char). like
else:
countChar_(str[1:], char)

But I have simply calling the function in the else block and some of the cases are failed, I want to know why is that

Hey @Supriya_Manna_AP2111 !

As it is a recursive function, implementing this function requires recursive calls. We need to make recursive calls in each section except for the base case. We have to return something to get to the final solution to the problem while using the recursive functions. The right code would be the following:

def countChar(str, char):
'''
you can call helper function as countChar_(str[1:], char)
'''
if len(str) <= 0:
  return 0
if str[0] == char:
return 1 + countChar_(str[1:], char)
else:
return countChar_(str[1:], char)

If you don’t use the return statement while calling the function, it will not return the value, which in turn causes the wrong output to be generated. That is why some of the test cases fail.