# # recursion_examples.py # # Example recursive functions from lecture # # Computer Science 111 # def power(b, p): """ returns b raised to the p power inputs: b is a number (int or float) p is a non-negative integer """ if p == 0: return 1 else: pow_rest = power(b, p-1) return b * pow_rest def mylen(s): """ returns the length of the sequence s input: s is a sequence (a string or list) """ if s == '' or s == []: return 0 else: len_rest = mylen(s[1:]) return 1 + len_rest def num_vowels(s): """ returns the number of vowels in the string s input: s is a string of 0 or more lowercase letters """ if s == '': return 0 else: num_in_rest = num_vowels(s[1:]) if s[0] in 'aeiou': return 1 + num_in_rest else: return 0 + num_in_rest def mymax(vals): """ returns the largest element in a list input: vals is a *non-empty* list """ if len(vals) == 1: return vals[0] else: max_in_rest = mymax(vals[1:]) if vals[0] > max_in_rest: return vals[0] else: return max_in_rest def replace(s, old, new): """ inputs: a string s two characters, old and new returns a version of s in which all occurrences of old old are replaced by new """ if s == '': return '' else: # the recursive call handles rest of string repl_rest = replace(s[1:], old, new) if s[0] == old: return new + repl_rest else: return s[0] + repl_rest