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

Count Vowels & Consonants Recursively

Count vowels and consonants recursively with carried totals. Students filter letters, lowercase each character, and return two values at the stopping index.

AdvancedPhase 3 - Level 4: String-based RecursionExample 9 of 10
count-vowels-consonants-recursively.py
1def count_vc(s, index=0, vowels=0, consonants=0):
2 # Base case
3 if index >= len(s):
4 return vowels, consonants
5
6 # Check current character
7 char = s[index].lower()
8 if char.isalpha():
9 if char in 'aeiou':
10 vowels += 1
11 else:
12 consonants += 1
13
14 # Recurse
15 return count_vc(s, index + 1, vowels, consonants)
16
17# Test
18text = input("Enter a string: ")
19v, c = count_vc(text)
20print(f"Vowels: {v}, Consonants: {c}")

Output

Enter a string: Hello
Vowels: 2, Consonants: 3

In this one

  • Carry two counters
  • Filter letters before vowels
  • Unpack a returned tuple

How it works

  1. 1

    Inspect the lowercase character at index.

  2. 2

    Increment the appropriate counter only for letters.

  3. 3

    Advance the index, then return both counters at the end.

Edge cases

Are digits counted as consonants?

Are digits counted as consonants?

No. They fail isalpha.

What does empty text return?

What does empty text return?

The pair zero, zero.

What's going on

The helper carries index, vowels, and consonants as arguments. isalpha excludes digits and punctuation before a letter is classified.

English vowels increase vowels; other alphabetic characters increase consonants under this code's rule. At the end, a tuple returns both totals for unpacking into v and c. The index advances on every character, and active calls occupy the stack.

Are digits counted as consonants? No. They fail isalpha.

What does empty text return? The pair zero, zero.

Quiz

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

Question 1

Why return two values?

Pick an answer to check it.

Question 2

Are digits counted as consonants?

Pick an answer to check it.

Questions people ask

Are digits counted as consonants?

No. They fail isalpha.

What does empty text return?

The pair zero, zero.

Why return two values?

Both counters are needed for the final message.