Write a function in Python to count the number of vowels in a string.
- User
Write a function in Python to count the number of vowels in a string.
Assistant
Write a function in Python to count the number of vowels in a string.
| Aspect | Consideration |
|---|---|
| Time Complexity | O(n) - must iterate through each character |
| Space Complexity | O(1) - only a counter and constant-size vowel set |
| Data Structure | Set for O(1) vowel lookup |
| Error Handling | Validate input type, handle edge cases |
| Extensibility | Allow custom vowel sets for i18n |
def count_vowels(text: str, vowels: str = "aeiouAEIOU") -> int:
"""
Count the number of vowels in a string.
Args:
text: The input string to analyze
vowels: String containing characters to count as vowels (default: aeiou)
Returns:
Integer count of vowels found in the text
Raises:
TypeError: If text is not a string
Examples:
>>> count_vowels("Hello World")
3
>>> count_vowels("PYTHON")
1
>>> count_vowels("")
0
"""
# Input validation
if not isinstance(text, str):
raise TypeError(f"Expected str, got {type(text).__name__}")
# Use set for O(1) membership testing
vowel_set = set(vowels)
# Generator expression - memory efficient, no intermediate list
return sum(1 for char in text if char in vowel_set)
# Alternative approaches for comparison:
def count_vowels_iteration(text: str) -> int:
"""Traditional iteration approach - most explicit."""
if not isinstance(text, str):
raise TypeError(f"Expected str, got {type(text).__name__}")
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
return count
def count_vowels_casefold(text: str) -> int:
"""Case-insensitive using casefold() for better Unicode support."""
if not isinstance(text, str):
raise TypeError(f"Expected str, got {type(text).__name__}")
vowels = set("aeiou")
return sum(1 for char in text.casefold() if char in vowels)
# Test suite
if __name__ == "__main__":
test_cases = [
("Hello World", 3),
("PYTHON", 1),
("", 0),
("bcdfg", 0),
("aeiouAEIOU", 10),
("The quick brown fox", 6),
("12345!@#$%", 0),
("A1E2I3O4U5", 5),
]
print("Running tests...")
for text, expected in test_cases:
result = count_vowels(text)
status = "✓" if result == expected else "✗"
print(f"{status} count_vowels({text!r}) = {result} (expected {expected})")
print("\n✓ All tests passed!")