Warming up: Lists and strings

Here are two sample problems and their solutions.

  1. Write a recursive function named reverse that takes a string parameter and returns the reverse of the string. For example:
    >>> reverse('maps')
    'spam'
    

    Solution:

    def reverse(text):
        """
        Uses a recursive strategy to reverse a string
    
        Args:
            text: a (possibly empty) string
    
        Returns:
            reverse of text
        """
    
        if len(text) <= 1:
            # base case
            # if string has one or zero characters, it is its own reverse
            return text
        else:
            # recursive case
            # remove the first character and concatenate it to end of 
            # recursively reversed rest of the string
            return reverse(text[1:]) + text[0]
    
  2. Write a recursive function named find (similar to the string method find we have used before) that takes as parameters two strings, and returns the index of the first occurrence of the second string in the first string. That is, find(text, substr) will look for substr in text, and return the first occurrence of substr in text, or -1 if not found. (You are not allowed to use any built-in string methods.) For example:
    >>> find("bird","z")
    -1
    >>> find("dog","d")
    0
    >>> find("mad man with a box", " ")
    3
    >>> find("she sells sea shells", "shel") 14

    Solution:

    def find(text, substr):
        """
        Uses a recursive strategy to search for substr in text
    
        Args:
            text: a string of characters (possibly empty)
            substr: a string of characters (possibly empty)
                
        Returns:
            the first index in text where substr is found, or -1 if not found
        """
    
        if len(text) < len(substr):
            # base case 1
            # if text is shorter than the substr, we won't find it
            return -1
    
        if text[:len(substr)] == substr:
            # base case 2
            # text starts with the substr, so return index 0
            return 0
    
        else:
            # recursive case
            # start of text isn't substr, so remove first letter and recursively find
            index = find(text[1:], substr)
                
            if index == -1:
                # substr was not found in text
                return -1
            else:
                # substr was found at position index in text[1:]
                # so is at position index+1 in text
                return index + 1