catalins.tech with Gatsby

[Coderbyte] – Vowel Count [Easy]

2019 Jan 28th

The “Vowel Count” is a popular and a self-explanatory challenge. Regardless, below is the challenge description taken from the Coderbyte website:

Have the function VowelCount(str) take the str string parameter being passed and return the number of vowels the string contains (ie. “All cows eat grass and moo” would return 8). Do not count y as a vowel for this challenge. 

Use the Parameter Testing feature in the box below to test your code with different arguments.

The key phrase for this coding challenge is “return the number of vowels the string contains“. Thus, the first logical step is to create a counter – a variable that is assigned the value 0, and it is incremented each time a vowel is found. That is done by the code on line 4 from the full solution.

The next step is to iterate over the given string, checking each character individually. When a character matches any vowel from the list – ‘a, e, i, o, u’ – then the count is incremented. One important thing to remember when comparing letters is to ensure they are both either uppercase or lowercase. If I would have used char instead of char.lower() on line 10, then the letter “A” would be different from “a”.

# iterate over each character from the given string
    for char in str:
        # if char is a vowel 
        #   increment count
        if char.lower() in 'a,e,i,o,u':
            count += 1

After all the characters are checked, the only thing left is to return the number of vowels found in the string. The full solution is below:

def VowelCount(str): 

    # count the vowels
    count = 0
    
    # iterate over each character from the given string
    for char in str:
        # if char is a vowel 
        #   increment count
        if char.lower() in 'a,e,i,o,u':
            count += 1
    
    # return the number of vowels
    return count

Starting with this post, I will post the Coderbyte’s official solution for each challenge I solve. They have taken the same approach with some differences (e.g. looping differently).

def VowelCount(str): 

  # convert the string to all lowercase characters
  str = str.lower()

  # possible vowels
  vowels = "aeiou"

  # where we store our vowel count
  count = 0

  # loop through the string checking each character
  for i in range(0, len(str)):
  
    # if this character is found in vowels string
    # then the character is a vowel and we add 1 to count 
    if str[i] in vowels:
      count = count + 1
  
  # return the number of vowels found
  return count