Numpy Exercise 2

Imports


In [1]:
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 [25]:
def np_fact(n):
    """Compute n! = n*(n-1)*...*1 using Numpy."""
    # YOUR CODE HERE
    a = np.arange(1, n+1, 1)   #Makes array from 1 to n+1
    if n==0:
        return 1               #If n is 1 or 0, returns value of 1.
    elif n==1:
        return 1
    else:
        return max(a.cumprod())#For all other n, takes max value of cumulative products
print np_fact(6)


720

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

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


In [43]:
def loop_fact(n):
    """Compute n! using a Python for loop."""
    # YOUR CODE HERE
    f = n
    if n == 0:
        return 1     #Same as above.
    elif n == 1:
        return 1
    while n > 1:
        f *= (n-1)   #For n > 1, takes continuous product of n to right before n = 0, otherwise it would all equal 0.
        n -= 1
    return f
    
print loop_fact(10)


3628800

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

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 [48]:
# YOUR CODE HERE
%timeit -n1 -r1 loop_fact(50)
%timeit -n1 -r1 np_fact(50)


1 loops, best of 1: 30 µs per loop
1 loops, best of 1: 149 µs per loop

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

YOUR ANSWER HERE: My loop_fact is faster, and I believe this is because the while function works inherently faster for small code than numpy does. np_fact is making a range of all values and then multiplyin them together, whil loop_fact is subtracts then multiplies without having to make an array.