Count Vowels in a String
Explore how to count the number of vowels in a string using both iterative and recursive methods in Python. This lesson helps you understand how to traverse strings, implement recursion, and compare these approaches, preparing you for coding interviews focused on recursion concepts.
We'll cover the following...
Problem Statement
Imagine that 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 methods.
Iterative Method
To solve this problem we have to traverse the entire string so that we can initiate a simple for loop.
Let’s take a look at the code:
In the code snippet above, the main function countVowels() takes a string as its input. It traverses the entire length of the string.
The condition
i in range(len(string))
ensures that the for loop breaks if i becomes equal to the length of the string calculated using len(string).
Next, we use a condition
isVowel(string[i])
to determine whether or not that particular character is a vowel. If this condition is satisfied, we increment count by .
isVowel() is a function that returns TRUE if the character it passes is a vowel. It returns FALSE if that character is not a vowel.
Recursive Method
Let’s take a look at the recursive counterpart:
The code will look something like this:
The isVowel() function checks whether or not the character being input to it is a vowel. The major change that occurs is the conversion of the for loop into the recursive call.
Each time, the length of the input string is reduced in the iterative method. This is also done in the recursive method. We reduce the length of the input string and pass another call of the same function. The leftover letter is examined to check if it is a vowel. The result is added in the function calls.
In the next lesson, we have a challenge for you to solve.