Problem overview
The function countVowels receives a string s and returns how many vowels it has. The vowels are a, e, i, o and u, in lower or upper case. The letter y is not a vowel here, and every other character, such as consonants, spaces, digits and punctuation, is skipped.
In "Hello World" the vowels are e, o and o, so the answer is 3. In "AlgoCademy" they are A, o, a and e, which makes 4: the capital A counts and the y doesn't. In "Why try?" there are none, so the answer is 0.
Approach
Look at each character in turn and decide whether it is a vowel. If it is, add one to a counter. To decide, keep all ten vowels, both cases, in one string, "aeiouAEIOU", and ask whether the character appears in it. Listing both cases avoids converting anything to lower case.
Python lets a for loop walk over a string directly, giving one character at a time, so no index is needed.
Step by step
- Store the vowels in a string named
vowels:"aeiouAEIOU". The letter y isn't in it. - Start
countat 0. Nothing has been checked yet. - Loop over
swith a variablec. Each turn,cis the next character. - If
c in vowels, add 1 tocount. The operatorinworks on strings: it isTruewhen the text on its left appears inside the text on its right. - Return
countafter the loop, so that every character has been checked first.
The solution in Python
class Solution:
def countVowels(self, s: str) -> int:
vowels = "aeiouAEIOU"
count = 0
for c in s:
if c in vowels:
count += 1
return count
Details worth knowing:
inon a string looks for a substring."e" in "aeiou"isTrueand"E" in "aeiou"isFalse, because the comparison is case-sensitive. That is why both cases are listed. Sincecis always a single character here, there is no surprise, but"ae" in "aeiou"isTruetoo, and so is the empty string"" in "aeiou".- Looping over a string.
for c in syields each character as a string of length 1. Spaces, digits and punctuation are characters like any other. They are just not invowels, so they are skipped. - An alternative with
lower().sum(1 for c in s if c.lower() in "aeiou")also gives 3 for"Hello World". The lesson's version spells out the loop. countis just a variable. Strings also have a method calledcount, but the name here belongs to the local variable. It doesn't clash with anything.
Edge cases and common mistakes
- Upper-case vowels. Checking only
"aeiou"would count"AlgoCademy"as 3 instead of 4. - The letter y.
"Why try?"returns 0, since y is not in the vowel string. - Returning inside the loop. A
returnindented under theifends the function at the first vowel, so the answer could never be more than 1. - Counting everything. Putting
count += 1outside theifcounts every character, not only the vowels. - Non-letters. A string like
"rhythm 123"returns 0. Digits and spaces are skipped without any special handling.
Testing
"Hello World"gives3."AlgoCademy"gives4."Why try?"gives0."AEIOU"gives5."rhythm 123"gives0.
