Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Vowels Recursively

Count English vowels recursively by advancing an index. Students use a string-length base case and combine one-character contributions into a returned count.

AdvancedPhase 3 - Level 4: String-based RecursionExample 3 of 10
count-vowels-recursively.py
1def count_vowels(s, index=0):
2 # Base case
3 if index >= len(s):
4 return 0
5
6 # Check current character
7 vowels = "aeiouAEIOU"
8 count = 0
9 if s[index] in vowels:
10 count = 1
11
12 # Recurse
13 return count + count_vowels(s, index + 1)
14
15# Test
16text = input("Enter a string: ")
17result = count_vowels(text)
18print(f"Number of vowels: {result}")

Output

Enter a string: Hello
Number of vowels: 2

In this one

  • Advance an index
  • Count character contributions
  • Use a length base case

How it works

  1. 1

    Return zero after the final index.

  2. 2

    Assign a one-or-zero contribution for the current vowel test.

  3. 3

    Add the count returned for index + 1.

Edge cases

What happens for empty text?

What happens for empty text?

The first call returns zero.

Does uppercase A count?

Does uppercase A count?

Yes. Both cases appear in the vowel string.

What's going on

The function checks s[index] against a string containing lowercase and uppercase vowels. A match contributes one; every other character contributes zero.

The next call advances index rather than slicing the input. When index reaches the length, zero ends the sum. For Sky the result is zero because y is not in this vowel set. Pending additions occupy the call stack.

What happens for empty text? The first call returns zero.

Does uppercase A count? Yes. Both cases appear in the vowel string.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What moves the scan forward?

Pick an answer to check it.

Question 2

What happens for empty text?

Pick an answer to check it.

Questions people ask

What happens for empty text?

The first call returns zero.

Does uppercase A count?

Yes. Both cases appear in the vowel string.

What moves the scan forward?

index + 1.