The Letter Census
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- Quantiphi
Problem
Given a string, return a dict with keys 'vowels' (count of a, e, i, o, u, case-insensitive) and 'consonants' (count of other alphabetic characters). Non-alphabetic chars are ignored.
Every crowd has its share of talkers and quiet ones.
Example 1
Input:
s = "Hello World"
Output:
{"vowels":3,"consonants":7}Example 2
Input:
s = "aeiou"
Output:
{"vowels":5,"consonants":0}Worked solution and explanation
Why this problem exists in real interviews
This tests character classification combined with counting, probing whether a candidate can separate vowels from consonants while ignoring non-alphabetic characters.
Break down the requirements
Step 1: Define the vowel set
Use a set {'a', 'e', 'i', 'o', 'u'} for O(1) lookups.
Step 2: Iterate and classify each character
Check if alphabetic first, then classify as vowel or consonant.
Step 3: Return counts in a dict
Keys are 'vowels' and 'consonants'.
The solution
def letter_census(s: str) -> dict:
vowels_set = {'a', 'e', 'i', 'o', 'u'}
vowel_count = 0
consonant_count = 0
for ch in s:
lower = ch.lower()
if lower.isalpha():
if lower in vowels_set:
vowel_count += 1
else:
consonant_count += 1
result = {'vowels': vowel_count, 'consonants': consonant_count}
return resultCommon follow-up questions
- What if you needed counts per character? (Tests switching to a full frequency dict.)
- How would you handle unicode vowels? (Tests awareness of accented characters like 'e' with acute.)
- What if the input is a file with millions of characters? (Tests streaming line-by-line processing.)