In [3]:
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 [4]:
def np_fact(n):
"""Compute n! = n*(n-1)*...*1 using Numpy."""
#Creates array from 1 to n
c = np.arange(1,n+1,1)
#Returns a 1D array of the factorials of each number
a = c.cumprod()
#Settles the 0 and 1 case
if n == 0 or n == 1:
return 1
#returns the last number in the array (The one we are looking for)
else:
return a[-1]
Out[4]:
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 [7]:
def loop_fact(n):
"""Compute n! using a Python for loop."""
#Creates a list from 0 to n
array = [0,n+1]
#i is a counting variable, number is the placeholder
i = 0
number = 1
#0 and 1 case
if n == 0 or n == 1:
return 1
#while i is less than the number count up to the number and multiply it by the previous numbers (number)
else:
while i < n:
i += 1
number = number * i
return number
In [8]:
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 [9]:
%timeit -n1 -r1 np_fact(50)
%timeit -n1 -r1 loop_fact(50)
In the cell below, summarize your timing tests. Which version is faster? Why do you think that version is faster?
loop_fact() is faster. This was the function that used python loops rather than numpy. This could be because the numpy function goes through an entire list of factorials while the python loop calculates one factorial in one loop.