Python Program to Determine How Many Times a Given Letter Occurs in a String Recursively

PythonServer Side ProgrammingProgramming

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.

Example

Below is a demonstration for the same −

 Live Demo

def check_frequency(my_str,my_ch):
   if not my_str:
      return 0
   elif my_str[0]==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))

Output

Enter the string :jaanea
Enter the character that needs to be checked :a
The frequency of a is :
3

Explanation

  • A method named ‘check_frequency’ is defined that takes a string and a character as parameters.
  • It checks to see if the characters in a string match the character passed to the method.
  • If they do, it is returned.
  • Else the method is called recursively on all characters of the string.
  • The string and the character are taken as user inputs.
  • The method is called by passing these values as parameters.
  • The output is dislayed on the console.
raja
Published on 12-Mar-2021 13:04:05
Advertisements