Lab 10 Notes

Review: How to Write a Recursive Function

  1. Define the function header, including the parameters
  2. Define the recursive case
  3. Define the base case
  4. Put it all together

Implementing a recursive minimum

Let’s develop a recursive implementation for min, named rec_min, that takes as a parameter a non-empty list (i.e., the input has at least one element):

  1. Define the function header, including the parameters

    def rec_min(a_list)
    """
    Returns the minimum value in a non-empty list
    """
    
    
  2. Define the recursive case

    The minimum value is the lesser of the first element and the recursive minimum of the rest of the list, i.e.

     min_rest = rec_min(a_list[1:])
     if min_rest < a_list[0]:
         return min_rest
     else:
         return a_list[0]
    
  3. Define the base case

    The minimum value of a list of length 1 is just the one and only value in the list

  4. Put it all together

     def rec_min(a_list):
         if len(a_list) == 1:
             return a_list[0]
         else:
             min_rest = rec_min(a_list[1:])
             if min_rest < a_list[0]:
                 return min_rest
             else:
                 return a_list[0]