December 10th, 2012, 02:37 AM
Im a noob at python, just got to recursion cannot figure this out
Rewrite the following function as a recursive function, keeping the same name and number of parameters:
VOWELS = "aeiou"
def vowel_count( s ):
count = 0
for c in s:
if c.lower() in VOWELS:
count = count + 1
December 10th, 2012, 08:38 AM
1) `in' is mathematically a set operation, and the search time is O(log(len(set))) instead of O(len(set))
2) Often you can replace `if' condition with arithmetic expression given that True is 1 and False is 0. See the very last line of my post 6.
3) About the recursion: Recursive functions need a way to stop. In this case if the length is 0 vc returns 0 which begins popping the stack.
4) If there is remaining length of the argument a call to vc processes one character and calls itself with a shortened string.
5) vc returns 1 or 0 + the vowel count of the remainder of the string.
VOWELS = set("aeiou")
def vowel_count(s): # non-recursive version
return sum(c in VOWELS for c in s.lower())
def vc(s): # recursive
return (s.lower() in VOWELS) + vc(s[1:])
[/code] are essential for python code and Makefiles!