Numpy Exercise 2

Imports


In [8]:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns

Factorial

Write a function that computes the factorial of small numbers using np.arange and np.cumprod.


In [20]:
def np_fact(n):
    """Compute n! = n*(n-1)*...*1 using Numpy."""
    np_fact.arange()
    np_fact.cumprod()

In [21]:
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]


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-c7ed3614e378> in <module>()
----> 1 assert np_fact(0)==1
      2 assert np_fact(1)==1
      3 assert np_fact(10)==3628800
      4 assert [np_fact(i) for i in range(0,11)]==[1,1,2,6,24,120,720,5040,40320,362880,3628800]

<ipython-input-20-74d50a45fce0> in np_fact(n)
      1 def np_fact(n):
      2     """Compute n! = n*(n-1)*...*1 using Numpy."""
----> 3     np_fact.arange(1,5)
      4     np_fact.cumsum()
      5 

AttributeError: 'function' object has no attribute 'arange'

Write a function that computes the factorial of small numbers using a Python loop.


In [35]:
def loop_fact(n):
    """Compute n! using a Python for loop."""
    n = int()
    fact = 1
    for i in range(1,n +1):
        fact = fact *i

In [36]:
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]


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-36-1e3be026136e> in <module>()
----> 1 assert loop_fact(0)==1
      2 assert loop_fact(1)==1
      3 assert loop_fact(10)==3628800
      4 assert [loop_fact(i) for i in range(0,11)]==[1,1,2,6,24,120,720,5040,40320,362880,3628800]

AssertionError: 

Use the %timeit magic to time both versions of this function for an argument of 50. The syntax for %timeit is:

%timeit -n1 -r1 function_to_time()

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()

In the cell below, summarize your timing tests. Which version is faster? Why do you think that version is faster?

YOUR ANSWER HERE