Counting vowels in a string using recursion

Posted by Daniel Love Jr on Stack Overflow See other posts from Stack Overflow or by Daniel Love Jr
Published on 2012-10-13T22:40:31Z Indexed on 2012/10/14 3:37 UTC
Read the original article Hit count: 190

Filed under:
|
|
|
|

In my python class we are learning about recursion. I understand that it's when a function calls itself, however for this particular assignment I can't figure out how exactly to get my function to call it self to get the desired results. I need to simply count the vowels in the string given to the function.

def recVowelCount(s):
    'return the number of vowels in s using a recursive computation'
    vowelcount = 0
    vowels = "aEiou".lower()
    if s[0] in vowels:
        vowelcount += 1
    else:
        ???

I'm really not sure where to go with this, it's quite frustrating.

I came up with this in the end, thanks to some insight from here.

def recVowelCount(s):
'return the number of vowels in s using a recursive computation'
vowels = "aeiouAEIOU"
if s == "":
    return 0
elif s[0] in vowels:
    return 1 + recVowelCount(s[1:])
else:
    return 0 + recVowelCount(s[1:])

© Stack Overflow or respective owner

Related posts about python

Related posts about string