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

When counting how many times a specific letter appears in a string, we can use recursion to break down the problem into smaller subproblems. Recursion solves the bigger problem by computing results from smaller parts and combining them together.

Recursive Approach

The recursive function checks each character one by one. If the current character matches our target, we count it and continue with the rest of the string ?

def count_letter_recursive(text, target_letter):
    # Base case: empty string
    if not text:
        return 0
    # If first character matches, count it and recurse on remaining string
    elif text[0] == target_letter:
        return 1 + count_letter_recursive(text[1:], target_letter)
    # If no match, just recurse on remaining string
    else:
        return count_letter_recursive(text[1:], target_letter)

# Example usage
my_string = "programming"
my_char = "m"
result = count_letter_recursive(my_string, my_char)
print(f"The letter '{my_char}' appears {result} times in '{my_string}'")
The letter 'm' appears 2 times in 'programming'

How the Recursion Works

Let's trace through the execution with string "hello" and target letter "l" ?

def count_letter_recursive(text, target_letter, depth=0):
    indent = "  " * depth
    print(f"{indent}Checking: '{text}' for letter '{target_letter}'")
    
    if not text:
        print(f"{indent}Empty string - returning 0")
        return 0
    elif text[0] == target_letter:
        print(f"{indent}Found match! '{text[0]}' == '{target_letter}'")
        result = 1 + count_letter_recursive(text[1:], target_letter, depth + 1)
        print(f"{indent}Returning: 1 + {result - 1} = {result}")
        return result
    else:
        print(f"{indent}No match: '{text[0]}' != '{target_letter}'")
        result = count_letter_recursive(text[1:], target_letter, depth + 1)
        print(f"{indent}Returning: {result}")
        return result

# Trace the execution
count = count_letter_recursive("hello", "l")
print(f"\nFinal count: {count}")
Checking: 'hello' for letter 'l'
No match: 'h' != 'l'
  Checking: 'ello' for letter 'l'
  No match: 'e' != 'l'
    Checking: 'llo' for letter 'l'
    Found match! 'l' == 'l'
      Checking: 'lo' for letter 'l'
      Found match! 'l' == 'l'
        Checking: 'o' for letter 'l'
        No match: 'o' != 'l'
          Checking: '' for letter 'l'
          Empty string - returning 0
          Returning: 0
        Returning: 0
      Returning: 1 + 0 = 1
    Returning: 1 + 1 = 2
  Returning: 2
Returning: 2

Final count: 2

Multiple Examples

Here are several examples demonstrating the function with different inputs ?

def count_letter_recursive(text, target_letter):
    if not text:
        return 0
    elif text[0] == target_letter:
        return 1 + count_letter_recursive(text[1:], target_letter)
    else:
        return count_letter_recursive(text[1:], target_letter)

# Test cases
test_cases = [
    ("python", "y"),
    ("recursion", "r"),
    ("banana", "a"),
    ("hello world", "l"),
    ("", "x"),
    ("aaaaaa", "a")
]

for text, letter in test_cases:
    count = count_letter_recursive(text, letter)
    print(f"'{letter}' in '{text}': {count} times")
'y' in 'python': 1 times
'r' in 'recursion': 2 times
'a' in 'banana': 3 times
'l' in 'hello world': 3 times
'x' in '': 0 times
'a' in 'aaaaaa': 6 times

Key Points

  • Base case: Empty string returns 0 (no more characters to check)
  • Recursive case: Check first character and recurse on the remaining string
  • Match found: Add 1 to the count and continue recursion
  • No match: Continue recursion without incrementing count

Conclusion

Recursive letter counting works by examining one character at a time and combining results. The function efficiently breaks down the string into smaller subproblems until reaching the base case of an empty string.

---
Updated on: 2026-03-25T17:40:13+05:30

816 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements