In [2]:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
Write a function that computes the factorial of small numbers using np.arange
and np.cumprod
.
In [3]:
n=10
a=np.arange(1,n+1,1)
a.cumprod()
Out[3]:
In [4]:
def np_fact(n):
"""Compute n! = n*(n-1)*...*1 using Numpy."""
if n==0: #0! is 1
return 1
elif n==1: #1! is 1
return 1
else:
a=np.arange(2,n+1,1)
return a.cumprod()[n-2] #returns factorial with numpy at the last index
In [5]:
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 [6]:
def loop_fact(n):
"""Compute n! using a Python for loop."""
fact=1
for i in range(1,n+1): #using a for loop to calculate the factorial starting at 1
fact*=i
return fact
raise NotImplementedError()
In [7]:
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 [11]:
%timeit -n1 -r1 np_fact(500000) #timing the time to complete calculation
%timeit -n1 -r1 loop_fact(500000)
In the cell below, summarize your timing tests. Which version is faster? Why do you think that version is faster?
The for loop only took 11.9 microseconds while the np_fact took 52.9 microseconds. This is because with small numbers, the for loops iterates faster than the np.cumprod multiplies it. If number is large, >50000, the np_fact function will be much faster than the for loop.