I need to use recursion to find the number of vowels in a string. So if hello is entered I want it to return 2.
The problem I’m having is going to the next character in the string.
def recVowelCount(i):
count = 0
if i in 'aeiou':
count +=1
reVowelCount(i)
else:
reVowelCount(i)
return count
Here’s one way to do it using recursion 🙂
Now, the problem in your code is that
would be asking
if 'hello' in 'aeiou':, which isn’t very useful. You need to checkif i[0] in 'aeiou'wherei[0]will be each letter of"hello"each time the function is called recursivelyStart with the simple case. What happens if the input string is empty? You’d just return
0right?So we’re half done. Now you need to think about what happens in the case the
iisn’t empty. If the first character is a vowel, we’ll count1and then pass the rest of the string into the function recursivelyok.. that can be refactored a little
and finally