Skip to main content

Problem 8: Count Vowels

Published 2 min readMarkdown
Part of seriesLearning how to code with AI
Problem 8: Count Vowels

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 return 3

  • count_vowels("AEIOU") should return 5

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:

  1. def count_vowels(s):

    • Defines a function named count_vowels that takes one parameter s (a string).
  2. 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.

  3. count = 0

    • Initializes a counter variable count to 0.
  4. for char in s:

    • Iterates through each character in the input string s.
  5. if char in vowels:

    • Checks if the current character exists in the vowels set.
  6. count += 1

    • If the character is a vowel, increments the count by 1.
  7. return count

    • Returns the final count of vowels.

Example Walkthrough with "pooopcycle"

  1. char is 'p', not in vowels.

  2. char is 'o', in vowels -> count becomes 1.

  3. char is 'o', in vowels -> count becomes 2.

  4. char is 'o', in vowels -> count becomes 3.

  5. char is 'p', not in vowels.

  6. char is 'c', not in vowels.

  7. char is 'y', not in vowels.

  8. char is 'c', not in vowels.

  9. char is 'l', not in vowels.

  10. char is 'e', in vowels -> count becomes 4.

  11. Returns 4.


Happy coding! 💻

About the author

  • Python Developer | Audio Editor | Technical Writer | OSS Contributor | Tag Moderator @ @ThePracticalDEV | Valorant TonyPoppins #881488

No comments yet. Be the first to comment.

Learning how to code with AI

Part 9 of 15

In this series, I’ll solve AI-generated Python challenges — from pseudo code to final solution — to rebuild my problem-solving skills, sharpen logic, and show how AI can help us learn to think like real developers again.

Up nextProblem 9: Most Frequent ElementHey everyone! 👋 Today, we're looking at a common problem in data processing: finding the Most Frequent Element in a list. The Problem The goal is to write a function that identifies which element appears most often in a given list. If there's a tie,...

More from this blog