Exercise 1: Documentation and Testing

The following little program needs some documentation and some tests. Since you didn't write it, I'll tell you what it's supposed to do. You'll need to document it. Feel free to test for additional exceptions if you have time but start with it as it is.

The point of the program is to compute the $L_{2}$ norm of a vector $v$. A second argument, if provided, will be interpreted as a vector of weights. The second argument must have the same length as the input vector.

NOTE: The input type of the vectors for this program should be a list of numbers.

As a reminder, the weighted $L_2$ norm of a vector $v$ is given by \begin{align*} \|v\|_{W} = \sqrt{\sum_{i=1}^{N}{\left(w_{i}v_{i}\right)^2}} \end{align*} where $N$ is the length of the vector $v$, $v_{i}$ is the i-th component of the vector $v$ and $w_{i}$ is the i-th component of the weight vector.

You must write the documentation and a decent test suite. Try to include some doctests as well!

Next, use the pytest module to run the doctests and unit tests and to assess the code coverage.

If you don't already have pytest, you can install it using pip install pytest. If you have trouble installing, here's the website: pytest installation.


In [1]:
import numpy as np

def L2(v, *args):
    s = 0.0 # Initialize sum
    if len(args) == 0: # No weight vector
        for vi in v:
            s += vi * vi
    else: # Weight vector present
        w = args[0] # Get the weight vector
        if (len(w) != len(v)): # Check lengths of lists
            raise ValueError("Length of list of weights must match length of target list.")
        for i, vi in enumerate(v):
            s += w[i] * w[i] * vi * vi
    return np.sqrt(s)