Search⌘ K
AI Features

Solution: Count the Number of Vowels in a String

Explore how to use recursion in Python to count the number of vowels in a string. Understand the base case for termination and how the function checks each character, incrementing counts and calling itself to process the entire string recursively.

We'll cover the following...

The solution to the problem of counting the number of vowels in a string is given below.

Solution

Python 3.8
def counts_vowels(s, idx, count) :
if idx == len(s):
return count
if s[idx] == 'a' or s[idx] == 'e' or s[idx] == 'i' or s[idx] == 'o' or s[idx] == 'u' :
count += 1
count = counts_vowels(s, idx + 1, count)
return count
count = counts_vowels('Raindrops on roses', 0, 0)
print(count)

Explanation

  • Lines
...