# lec14.py # Lillian Lee (LJL2) # Mar 12, 2014 """Demo recursive functions.""" import random def num_es(s): """Returns: number of 'e's in string s.""" # A non-tricky recursion on the "back end" of the string # Idea: if s has at least one letter, let startcount = e-count in s[0] # If s has at least two letters, return startcount plus e-count of s[1:] if s=='': # a base case return 0 else: # s has at least one character startcount = (1 if s[0] == 'e' else 0) if len(s) == 1: # another base case return startcount else: # recursive case, s has at least 2 characters return startcount + num_es(s[1:]) def num_es_compact(s): """Returns: number of 'e's in string s.""" # A condensed-code implementation if s=='': # a base case return 0 else: return (1 if s[0] == 'e' else 0) + num_es_compact(s[1:]) def num_es_middle(s): """Returns: number of 'e's in string s.""" # This implementation uses a random 'split point' to make two recursive calls # on two smaller substrings. # For a string s of length >=2, i = random.randrange(1,len(s)) sets i an # int between 1 and ***len(s)-1***, inclusive, so s[i:] is nonempty, as is # s[:i]. if len(s) < 2: # {base case: can't break into two smaller strings} return (1 if s == 'e' else 0) else: # s has at least 2 characters. Must be careful to choose a 'split point' that makes # progress towards the base case: two smaller substrings i = random.randrange(1,len(s)) # {i in 1..len(s)-1}, so s[:i] != '' print s + '->' + str(s[:i]) + ' and ' + str(s[i:]) return num_es_middle(s[:i]) + num_es_middle(s[i:]) # Useful thing to add in lecture: # print s + '->' + str(s[:i]) + ' and ' + str(s[i:]) def ispalindrome(s): """Returns: True if s is a palindrome, False otherwise. Case differences count as mismatched Pre: s is a string""" if len(s) < 2: return True else: # at least two characters in s return s[0] == s[-1] and ispalindrome(s[1:-1]) def reverse(s): """Returns: reverse of string s""" # base case if s == '': return s # idea: reverse of string is reverse(s[1:]) + s[0] return reverse(s[1:]) + s[0] def reverse2(s): """Returns: reverse of string s""" # alternate implementation if len(s) <= 1: return s return s[-1] + reverse(s[:-1])