Learn Programming and technology with ease @ developerpublish.com

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

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

In this Python program, weâ€™ll create a recursive function to determine how many times a given letter occurs in a string.

## Problem Statement:

You need to write a Python program that calculates the frequency of a given letter in a given string using a recursive approach.

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

```def count_letter_recursive(word, letter):
if len(word) == 0:
return 0
elif word[0] == letter:
return 1 + count_letter_recursive(word[1:], letter)
else:
return count_letter_recursive(word[1:], letter)

# Input
input_word = input("Enter a word: ")
input_letter = input("Enter the letter to count: ")

# Count the occurrences
result = count_letter_recursive(input_word, input_letter)
print(f"The letter '{input_letter}' occurs {result} times in the word '{input_word}'."      ```

## How it Works:

The program defines a recursive function count_letter_recursive that takes a word and a letter as arguments. It uses the base case of an empty word, returning 0, and two recursive cases: one where the first letter matches the given letter, incrementing the count and calling the function with the rest of the word, and another where the first letter doesnâ€™t match, and only the function with the rest of the word is called.

## Input/Output:

Enter a word: Banana

Enter the letter to count: a

The letter â€˜aâ€™ occurs 3 times in the word â€˜Bananaâ€™.

### You May Also Like

#### Python Program to Remove Duplicates from a Linked List

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...

#### Python Program to Solve the Celebrity Problem

This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...

#### Python Program to Solve n-Queen Problem with Recursion

This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...