# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python [conda root]
#     language: python
#     name: conda-root-py
# ---

# # 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](https://docs.pytest.org/en/latest/getting-started.html).

# +
import numpy as np

def L2(v, *args):
    """Returns the L2 norm of a vector v
    
    INPUTS
    =======
    v: list
       Vector of which the L2 norm to be calculated
    *arg: list, optional
       Weight vector
       
    RETURNS
    ========
    L2_norm: float
       float unless len(v) != len(args[0])
       in which case a ValueError exception is raised
       
    EXAMPLES
    =========
    >>> L2([3, 4])
    5.0
    >>> L2([3, 4], [1, 1])
    5.0
    """
    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)


# -

import pydoc
pydoc.doc(L2)

import doctest
doctest.testmod(verbose=True)


# +
def test_L2_result():
    assert L2([3, 4]) == 5.0
    assert L2([3, 4], [1, 1]) == 5.0

test_L2_result()


# +
def test_L2_types():
    try:
        L2(10)
    except TypeError as err:
        assert(type(err) == TypeError)
    
test_L2_types()


# +
def test_L2_difflength():
    try:
        L2([1, 1], [1, 1, 1])
    except ValueError as err:
        assert(type(err) == ValueError)

test_L2_difflength()

# +
# %%file L2.py
import numpy as np

def L2(v, *args):
    """Returns the L2 norm of a vector v
    
    INPUTS
    =======
    v: list
       Vector of which the L2 norm to be calculated
    *arg: list, optional
       Weight vector
       
    RETURNS
    ========
    L2_norm: float
       float unless len(v) != len(args[0])
       in which case a ValueError exception is raised
       
    EXAMPLES
    =========
    >>> L2([3, 4])
    5.0
    >>> L2([3, 4], [1, 1])
    5.0
    """
    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)


# +
# %%file test_L2.py
import L2

def test_L2_result():
    assert L2.L2([3, 4]) == 5.0
    assert L2.L2([3, 4], [1, 1]) == 5
    
    
def test_L2_types():
    try:
        L2.L2(10)
    except TypeError as err:
        assert(type(err) == TypeError)

def test_L2_difflength():
    try:
        L2.L2([1, 1], [1, 1, 1])
    except ValueError as err:
        assert(type(err) == ValueError)
# -

# !pytest

StarcoderdataJupyterScriptsDedupFiltered