BudiBadu Logo

Count Vowels in a String

Python Easy 12 views
Like0

In this problem, you will learn how to iterate through a string and use conditionals to check for specific characters. String manipulation and counting occurrences are common tasks in programming, especially when parsing text or analyzing user input.

Your objective is to write a function that accepts a string and returns the total number of vowels (A, E, I, O, U, both uppercase and lowercase) present in the string. You should initialize a counter, iterate over every character in the string, and increment the counter each time a vowel is encountered.

There are multiple ways to solve this. You can use a traditional for loop, or you can leverage Python's built-in sum() combined with a generator expression for a more compact and elegant solution.

Algorithm Flow

Recommendation Algorithm Flow for Count Vowels in a String - Budibadu
Recommendation Algorithm Flow for Count Vowels in a String - Budibadu

Best Answers

python - Approach 1
def count_vowels(text):
    # Approach 1: Generator expression
    vowels = set('aeiouAEIOU')
    return sum(1 for char in text if char in vowels)