# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 2
#     language: python
#     name: python2
# ---

# + [markdown] nbgrader={}
# # Numpy Exercise 2

# + [markdown] nbgrader={}
# ## Imports

# + nbgrader={}
import numpy as np
# %matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
# -

import antipackage
import github.ellisonbg.misc.vizarray as va


# + [markdown] nbgrader={}
# ## Factorial

# + [markdown] nbgrader={}
# Write a function that computes the factorial of small numbers using `np.arange` and `np.cumprod`.

# + nbgrader={"checksum": "4e72a0f70d32914a77d8d31ae0c2fb5a", "solution": true}
def np_fact(n):
    if n == 0:
        return 1
    elif n == 1:
        return 1
    else:
        a = np.arange(1,n+1,1)
        b = a.cumprod()
    return b[-1]


# + deletable=false nbgrader={"checksum": "fcb54de452abd89e3b1818a34678d4b4", "grade": true, "grade_id": "numpyex02a", "points": 4}
assert np_fact(0)==1
assert np_fact(1)==1
assert np_fact(10)==3628800
assert [np_fact(i) for i in range(0,11)]==[1,1,2,6,24,120,720,5040,40320,362880,3628800]


# + [markdown] nbgrader={}
# Write a function that computes the factorial of small numbers using a Python loop.

# + nbgrader={"checksum": "9341aa5eb68a3ce57e5cce1cd9192021", "solution": true}
def loop_fact(n):
    if n == 0:
        return 1
    elif n == 1:
        return 1
    else:
        a = 1
        while n >= 1:
            a = n * a
            n = n - 1
        return a


# + deletable=false nbgrader={"checksum": "a9946f0fdca1abf66ddfb0454ab10113", "grade": true, "grade_id": "numpyex02b", "points": 4}
assert loop_fact(0)==1
assert loop_fact(1)==1
assert loop_fact(10)==3628800
assert [loop_fact(i) for i in range(0,11)]==[1,1,2,6,24,120,720,5040,40320,362880,3628800]

# + [markdown] nbgrader={}
# Use the `%timeit` magic to time both versions of this function for an argument of `50`. The syntax for `%timeit` is:
#
# ```python
# # # %timeit -n1 -r1 function_to_time()
# ```

# + deletable=false nbgrader={"checksum": "6cff4e8e53b15273846c3aecaea84a3d", "solution": true}
# YOUR CODE HERE
# %timeit -n1 -r1 (loop_fact)

# %timeit -n1 -r1 (np_fact)

# + [markdown] nbgrader={}
# In the cell below, summarize your timing tests. Which version is faster? Why do you think that version is faster?

# + [markdown] deletable=false nbgrader={"checksum": "84e52188175a63ea7106817b9b063eef", "grade": true, "grade_id": "numpyex02c", "points": 2, "solution": true}
# np_fact is faster, but by a very small amount of time.  np_fact is faster because it does not loop through each iteration of the loop like np_loop does.  Instead, I called the cumprod function, which acts on the entire array at the same time.

StarcoderdataJupyterScriptsDedupFiltered