Hey everyone! π
Today, we're tackling a string manipulation problem: Counting Vowels.
The Problem
The goal is to write a function that counts the number of vowels in a given string. We need to consider both lowercase and uppercase vowels ('a', 'e', 'i', 'o', 'u').
Example:
-
count_vowels("hello world")should return3 -
count_vowels("AEIOU")should return5
The Solution
Here is the Python implementation:
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
Code Breakdown
Let's walk through the code line by line:
-
def count_vowels(s):- Defines a function named
count_vowelsthat takes one parameters(a string).
- Defines a function named
-
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}- Creates a set containing all vowels (both lowercase and uppercase).
- Using a set allows for efficient O(1) lookups.
-
count = 0- Initializes a counter variable
countto 0.
- Initializes a counter variable
-
for char in s:- Iterates through each character in the input string
s.
- Iterates through each character in the input string
-
if char in vowels:- Checks if the current character exists in the
vowelsset.
- Checks if the current character exists in the
-
count += 1- If the character is a vowel, increments the
countby 1.
- If the character is a vowel, increments the
-
return count- Returns the final count of vowels.
Example Walkthrough with "pooopcycle"
-
charis 'p', not in vowels. -
charis 'o', in vowels ->countbecomes 1. -
charis 'o', in vowels ->countbecomes 2. -
charis 'o', in vowels ->countbecomes 3. -
charis 'p', not in vowels. -
charis 'c', not in vowels. -
charis 'y', not in vowels. -
charis 'c', not in vowels. -
charis 'l', not in vowels. -
charis 'e', in vowels ->countbecomes 4. - Returns
4.
Happy coding! π»
Top comments (0)