Vowel Counter
Easy · 30 XPCount the vowels (a, e, i, o, u) in the string "programming in python is productive" and print the count.
10
sum(1 for ch in text if ch in "aeiou")
text = "programming in python is productive" print(sum(1 for ch in text if ch in "aeiou"))
Run your code to check it…
How to approach Vowel Counter
Counting is a loop with a condition and a tally. Walk the string one character at a time, ask whether that character is a vowel, and add one when it is.
The neat Python test for "is this one of these characters" is membership: ch in "aeiou". Wrapped in a generator, sum(1 for ch in text if ch in "aeiou") does the walk, the test and the tally in a single expression. Writing it first as a plain for loop with a counter is a good way to see what that expression is doing.
Worked through on this data
- "programming" has o, a, i: 3 vowels.
- "in" has i: running total 4. "python" has o: total 5 (y is not on the list).
- "is" has i: total 6. "productive" has o, u, i, e: total 10, the target output.
Common mistakes
- Uppercase letters slip through: "Apple" has two vowels, but
"A" in "aeiou"is False. Calltext.lower()first when the input can contain capitals. - Counting
yas a vowel gives 11 here. Decide the rule from the prompt, not from intuition. text.count("aeiou")looks for the five-letter substring "aeiou", not for each vowel, and returns 0.
Time and space
One pass over the string: O(n) time. Membership in a five-character string is effectively constant, and the generator stores nothing, so extra space is O(1).
Where this shows up
Character classification is the first step of every tokenizer, password-strength checker and input validator: count the digits, reject the control characters, flag the non-ASCII letters.
Take it further
Print a count for each vowel separately, in a b c order, using collections.Counter on just the vowel characters.