Numpy Exercise 2

Imports


In [2]:
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 [28]:
def np_fact(n):
    a = np.arange(1, n + 1)
    b = 1
    if n > 0:
        b = a.cumprod()
        return b[-1]
    else:
        return b

print np_fact(10)


3628800

In [21]:
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 [22]:
def loop_fact(n):
    c = list(range(1, n + 1))
    d = 1
    if n == 0:
        return d
    else:
        for item in c:
            d = d * item
    return d

print loop_fact(10)


3628800

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


1 loops, best of 1: 58.9 µs per loop
1 loops, best of 1: 36 µs per loop

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

The array version was consistently slower than the loop version, the array one was probably supposed to be faster. Arrays might be faster because they involve only 1 datatype, so python doesn't have to check what type of data it's running for every item in a loop.