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 [4]:
def np_fact(n):
if n == 0:
return 1
else:
#This puts the numbers 1 to n in steps of one in an array
numbers = np.arange(1.0, n+1, 1.0)
#The cumprod command makes a list of the factorials up to n!
#The [-1] call takes the last element in the array (n!)
product = numbers.cumprod(0)[-1]
return product
np_fact(6)
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 [6]:
def loop_fact(n):
answer = 1
for i in range(n):
#The answer is multipled by 1 to n (n!)
answer = answer * (i+1)
return answer
loop_fact(6)
Out[6]:
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 [9]:
%timeit -n1 -r1 np_fact(5)
%timeit -n1 -r1 loop_fact(5)
In the cell below, summarize your timing tests. Which version is faster? Why do you think that version is faster?
In np_fact, the computer must first create an array of elements 1, 2, ... (n-1) to n. Then, the cumprod function creates an array of all the factorials to n! (1!, 2!,... (n-1)!, n!).
In loop_fact, the computer takes each numbers 0 to (n-1), adds one to it and multiplies it to a variable, n times.
np_fact is slower because it has a greater amount of operations to complete. loop_fact is more simple, as it requires taking an integer in a range, adding one, multiplying by a variable and reassigning the variabe. Whereas in np_fact, a range of numbers is divided by step size, then cumprod creates an array containing each number's factorial and I only call the last element in that array.