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]:
def np_fact(n):
"""Compute n! = n*(n-1)*...*1 using Numpy."""
#using these seperate cases seems needlessly complex, but it should work for all numbers (return 0 if n is negative)
if n > 1:
a = np.arange(1, n + 1, 1)
return np.cumprod(a)[-1]
elif n == 0 or n == 1:
return 1
else:
return 0
In [4]:
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 [5]:
def loop_fact(n):
prod = 1
if n >= 0:
for x in range(1,n+1):
prod = prod*x
return prod
#again, returns zero if factorial is taken of a negative number
else:
return 0
In [6]:
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]:
# YOUR CODE HERE
%timeit -n1 -r1 loop_fact(1000)
%timeit -n1 -r1 np_fact(1000)
In the cell below, summarize your timing tests. Which version is faster? Why do you think that version is faster?
The Python loop version seems faster, usually around 2-4 times faster. This may be simply because the loop version only deals with the final product, while the numpy version creates an entire array and takes the answer from the last entry. This requires unnecessary memory, and can slow down the process.