Reputation: 38
def count_vowels(s):
if not s:
return 0
elif s[0] in VOWELS:
return 1 + count_vowels(s[1:])
else:
return 0 + count_vowels(s[1:])
I see that this code works perfectly fine for finding the number of vowels in a string. I also understand recursion always calls for a base case. I guess my main problem with this code is what does the first if statement actually mean? What is it checking?
if not s:
return 0
if what not s? Is there any way to write the code without that portion?
Upvotes: 1
Views: 1175
Reputation: 222641
This is your exit from recursion. Your recursion has to stop at some point of time (otherwise it will run forever).
It means that if the string is empty - return 0 (there are no vowels in empty string) and stop.
Upvotes: 2
Reputation: 76792
if not s
checks if the string is empty. Empty strings are "false-y" objects in Python. If the string is empty, it must not have any vowels.
I realize you are probably required to use recursion here, but this would be a better way to do it in practice:
>>> VOWELS = set('aeiou')
>>> def count_vowels(s):
... return sum(x in VOWELS for x in s)
...
>>> count_vowels('hello world')
3
Upvotes: 1