# # a set of recursive functions # Matt Bishop, MHI 289I, Winter 2018 # # find the length of a string # assumes argument passed in is a string def length(s): # base case: empty string has length 0 if s == "": return 0 # now express the length as involving the length of a shorter string return 1 + length(s[1:]) # returns True if string is composed of letters *only*, False otherwise # assumes argument passed in is a string def onlyalpha(s): # base case: empty string is trivally composed of letters if s == "": return True # now see if the first is alphabetic; if so, check rest of string return s[0].isalpha() and onlyalpha(s[1:]) # find the maximum element of a list # assumes argument passed in is a list and all elements in it are comparable def largest(l): # base case: list of 1 element, return that element if len(l) == 1: return l[0] # now return the larger of the first element and the largest element # in the rest of the list lrest = largest(l[1:]) if lrest < l[0]: return l[0] else: return lrest # construct a string by catenating elements of a list (like ''.join(s)) # assumes argument passed in is a list of strings def makestring(l): # base case: empty list gives empty string if l == []: return "" # otherwise, append the string formed by the rest of the list # to the first element return l[0] + makestring(l[1:]) # returns the string, reversed # assumes argument passed in is a string def revstr(s): # base case: empty list gives same reverse if s == "": return "" # otherwise, peel off last char, reverse rest, prepend what you peeled off return s[-1] + revstr(s[:-1])