Problem 8: Count Vowels
Source: Dev.to
Examples
count_vowels("hello world") # โ 3
count_vowels("AEIOU") # โ 5
Solution
def count_vowels(s):
"""
Counts the number of vowels in a string.
"""
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
count = 0
for char in s:
if char in vowels:
count += 1
return count
# Test case
print(count_vowels("pooopcycle")) # Output: 4
Walkthrough
-
Function definition:
def count_vowels(s):creates a function that accepts a strings. -
Vowel set:
vowels = {...}stores all lowercase and uppercase vowels in a set for O(1) lookups. -
Counter initialization:
count = 0starts the vowel counter. -
Iteration:
for char in s:loops through each character in the input string. -
Check & increment:
if char in vowels: count += 1Increments
countwhen the current character is a vowel. -
Return:
return countprovides the total number of vowels found.
Example trace for "pooopcycle"
| Character | In vowels? | Count |
|---|---|---|
| p | No | 0 |
| o | Yes | 1 |
| o | Yes | 2 |
| o | Yes | 3 |
| p | No | 3 |
| c | No | 3 |
| y | No | 3 |
| c | No | 3 |
| l | No | 3 |
| e | Yes | 4 |
The function correctly returns 4 for this input.
Happy coding! ๐ป