Count Vowels in a String
In this lesson, we will learn how to find the number of vowels in a string using recursion.
We'll cover the following
Problem Statement
We have to find the number of vowels in a given string. We know that the english alphabet contains vowels: . Let’s solve this problem using both iterative and recursive method.
Iterative Method
To solve this problem we have to traverse the entire string. Therefore we can initiate a simple for
loop.
Let’s have a look at the code:
def isVowel(character): # function to check whether input character is a vowelcharacter = character.lower() # convert character to lower case so upper cases can also be handledvowels = "aeiou" # string containing all vowelsif character in vowels: # check if given character is in vowelsreturn 1else:return 0def countVowels(string): # function that returns the count of vowelscount = 0for i in range(len(string)):if isVowel(string[i]) : # check if character is vowelcount += 1return count# Driver codestring = "Educative"print(countVowels(string))
In the code snippet above, the main function countVowels()
takes a string
as input. It traverses over the entire length of the string.
The condition:
i in range(len(string))
makes sure that the for
loop breaks if i
becomes equal to the length of string, calculated by using len(string)
.
Next, we use a condition:
isVowel(string[i])
to determine whether that particular character is a vowel or not. If this condition is satisfied we increment count
by .
isVowel()
is a function that returns TRUE
if the character being passed is a vowel and FALSE
otherwise.
Recursive Method
Let’s have a look at the recursive counterpart:
The code will therefore look something like this:
def isVowel(character): # function to check whether input character is a vowelcharacter = character.lower() # convert character to lower case so upper cases can also be handledvowels = "aeiou" # string containing all vowelsif character in vowels : # check if given character is in vowelsreturn 1else:return 0def countVowels(string, n): # function that returns the count of vowels# Base Caseif n == 1 :return isVowel(string[0])# Recursive Casereturn countVowels(string, n - 1) + isVowel(string[n - 1])# Driver codestring = "Educative"print(countVowels(string, len(string)))
The isVowel()
function for checking whether the character being input to it is a vowel or not remains the same. The major change that occurs is the conversion of the for
loop to the recursive call.
Each time the length of the input string
was being reduced in the iterative method. We are doing the same in the recursive method. We reduce the length of the input string
and pass it another call of the same function. The leftover letter is checked whether it is a vowel or not and the result added in the function calls.
In the next lesson, we have a challenge for you to solve for yourself.