Exercises

  1. 11.1 What does the following code do?

    In [1]: def mystery(a, b):
       ...:     if b == 1:
       ...:        return a
       ...:     else:
       ...:        return a + mystery(a, b - 1)
       ...:
    
    In [2]: mystery(2, 10)
    Out[2]: ?????
  2. 11.2 Find the logic error(s) in the following recursive function, and explain how to correct it (them). This function should find the sum of the values from 0 to n.

    In [3]: def sum(n):
       ...:     if n == 0:
       ...:        return 0
       ...:     else:
       ...:        return n + sum(n)
       ...:
  3. 11.3 What does the following code do?

    In [4]: def mystery(a_array, size):
       ...:     if size == 1:
       ...:        return a_array[0]
       ...:     else:
       ...:        return a_array[size - 1] + mystery(a_array, size - 1)
       ...:
    In [5]: import numpy as np
    
    In [6]: numbers = np.arange(1, 11)
    
    In [7]: mystery(numbers, len(numbers)) ...

Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.