When it is required to check the number of times a given letter occurs in a string using recursion, a method can be defined, and an ‘if’ condition can be used.
The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.
Below is a demonstration for the same −
def check_frequency(my_str,my_ch): if not my_str: return 0 elif my_str==my_ch: return 1+check_frequency(my_str[1:],my_ch) else: return check_frequency(my_str[1:],my_ch) my_string = input("Enter the string :") my_char = input("Enter the character that needs to be checked :") print("The frequency of " + str(my_char) + " is :") print(check_frequency(my_string,my_char))
Enter the string :jaanea Enter the character that needs to be checked :a The frequency of a is : 3