# # Name: CS 111 Course Staff # # lab3task2.py # # # To debug this function, we start by observing that we get the following # error message when we call the function: # # RecursionError: maximum recursion depth exceeded in comparison # # This means that we're getting "infinite recursion" -- i.e., that we # keep making recursive calls, and that we never reach the base case. # # When this happens, there are two common causes: # # * there is a bug in the code that checks for the base case(s) # * there is a bug in the code that makes the recursive call, such that # the inputs to the function are not being properly reduced. # # Looking at the function, can you see which of these is the cause? # # (We notice that the base case is incorrectly checking for a space, # rather than for an empty string.) # # Once we eliminate the RecursionError, we should notice that we # still don't get the correct result. # # To help us debug, we can try putting a print statement on the first line # of the function to reveal what s is for every function call: # # print('starting call for', s) # # You can also do something similar before each return statement, and # include the value being returned. For example, here is something # you could add before the final return statement: # # print('call for', s, 'returns', num_in_rest) # # You should discover that this function is incorrectly adding 1 # when s[0] is a vowel, instead of when it is a consonant. # # Below is the fixed version: # def num_consonants(s): """ returns the number of consonants in s parameter: s is a string of lower-case letters """ if s == '': return 0 else: num_in_rest = num_consonants(s[1:]) if s[0] not in 'aeiou': return num_in_rest + 1 else: return num_in_rest