5.2. Exercises#

Note

You don’t need to worry about using Interactive Jupyter Notebooks for these exercises. You can simply ignore the rocket icon () and go ahead to answer the questions using the knowledge you’ve gained from the chapter. Have fun!

5.2.1. Exercise 5.1.1#

In the code cell bellow you can see a function that finds the greatest common divisor of any two numbers using the math module.

import math

def find_greatest_common_divisor(a, b):
    greatest_common_divisor = math.gcds(a, b)
    return greatest_common_divisor

print('The greatest common divisor is:', find_greatest_common_divisor(2, 4))

5.2.2. (Searching) Exercise 5.1.2#

We can only take and store measurements at a limited number of locations and/or times. But what if we are interested in a value in between, i.e., at a location/time where we do not have a measurement? Then we can use interpolation to estimate that value. A popular, and simple, interpolation technique is linear interpolation. Your task is to use the module scipy to perform a 1D linear interpolation between a set of known points, where x_known and y_known are arrays with the measured \(x\) and \(y\) values. Use Google to look up the 1D interpolation function in scipy.

In the code below there is something missing after return (look the three dots). What should be the correct missing code for the function to give us the desired result?

from scipy import interpolate

def interpolate_inbetween(x_known, y_known, x_predict):
    f = interpolate.interp1d(x_known, y_known)
    return ...

5.2.3. (Searching) Exercise 5.1.3#

Now, let’s try to measure the running time of a function, for that we will need the time module. Use it to measure the working time of the cool_function() below.

# you do not need to change anything in this cell
def cool_function():
    x = 0
    for i in range(100000000):
        x += 1

Which of the following functions will give us the working time of the cool_function()?

  • Option A

def measure_time(func):
    t0 = time.time()
    t1 = time.time()
    return t1 - t0
  • Option B

def measure_time(func):
    t0 = time.time()
    func()
    t1 = time.time()
    return t1 - t0
  • Option C

def measure_time(func,t0,t1):
    t0 = time.time()
    func()
    t1 = time.time()
    return func