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 [14]:
def np_fact(n):
    """Compute n! = n*(n-1)*...*1 using Numpy."""
    numbers=np.arange(1,n+2) #creates an array with numbers up to n+1
    a=numbers.cumprod() #makes a the running product of the previous numbers. 
    fact=a[n-1] #selects the second to last product which is the factorial of n
    return fact

In [15]:
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 [16]:
def loop_fact(n):
    """Compute n! using a Python for loop."""
    # YOUR CODE HERE
    if n==0:  #defines the case when n=0
        fact=1
    else: 
        fact=n # sets fact equal to n 
        i=n-1 
        while i>0: #while i is greater than zero multiplies i by n and then decreses i
            fact=fact*i
            i-=1
    return fact

In [17]:
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 [43]:
%timeit -n1 -r1 loop_fact(50)


1 loops, best of 1: 14.1 µs per loop

In [44]:
%timeit -n1 -r1 np_fact(50)


1 loops, best of 1: 89.9 µs per loop

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

My function loop_fact, which computes the factorial of n using a while loop and an if/else statement takes 14.1us to run. My funciton np_fact, which achieves the same result but by using array functions takes 89.9us to run. This is roughly 6 times slower. This doesn't make sense, since I was under the impression that it should be the opposite.


In [ ]: