Practice Exercises 9 For the week of 2020-04-20

The following exercises provide additional practice problems (not to turn in) for our material this week. Try to solve each problem on paper first before using Thonny to confirm your answers. You are encouraged to work on these practice exercises with classmates throughout the week. Solutions here.

  1. Write a function named rec_in that takes two parameters, a list and an item, and returns True if that item is in the list, and False otherwise. Like the lab assignment, you must implement this recursively (no loops!) and should not use functions like index, count, or in.

  2. Write the docstring for the following recursive function:

     def mystery(a_list):
         if len(a_list) <= 1:
             return True
         else:
             return (a_list[0] <= a_list[1]) and mystery(a_list[1:])
    

    Try to describe the recursive relationship in a single sentence.

  3. The Fibonacci numbers are the following:

    1, 1, 2, 3, 5, 8, 13, 21, ...
    

    The nth Fibonacci number is defined as the sum of the previous two Fibonacci numbers (and the first two numbers are both 1). So, the 3rd Fibonacci number is 2, the 4th Fibonacci number is 3, etc.

    Write a function named fib that takes a number n as a parameter and returns the nth Fibonacci number. Your function must be a recursive function.

  4. Your recursive fib function calculates the correct answer, but isn’t efficient. Try calling your function to calculate the 100th Fibonacci number. Why is your recursive implementation so slow?

    To help answer this question count how many times fib would be called when you invoke fib(5).