Here's one way to do it using recursion :)
def recVowelCount(i, chars_to_find='aeiou'):
if not chars_to_find:
return 0
return i.count(chars_to_find[0]) + recVowelCount(i, chars_to_find[1:])
Now, the problem in your code is that
if i in 'aeiou':
would be asking if 'hello' in 'aeiou':
, which isn't very useful. You need to check if i[0] in 'aeiou'
where i[0]
will be each letter of "hello"
each time the function is called recursively
Start with the simple case. What happens if the input string is empty? You'd just return 0
right?
def recVowelCount(i):
if not i:
return 0
So we're half done. Now you need to think about what happens in the case the i
isn't empty. If the first character is a vowel, we'll count 1
and then pass the rest of the string into the function recursively
def recVowelCount(i):
if not i:
return 0
if i[0] in 'aeiou':
count = 1
else:
count = 0
return count + recVowelCount(i[1:])
ok.. that can be refactored a little
def recVowelCount(i):
if not i:
return 0
count = 'aeiou'.count(i[0])
return count + recVowelCount(i[1:])
and finally
def recVowelCount(i):
if not i:
return 0
return 'aeiou'.count(i[0]) + recVowelCount(i[1:])