In [7]:
# for ipython notebooks this display images inline and imports
# numpy and matplotlib
%pylab inline
# ----- Future Libraries for Python 3 portability
from __future__ import print_function
from future.builtins import range
# ---- Standard Libraries (not imported by pylab)
import time
# ---- Scientific Libraries (not imported by pylab)
import pandas as pd
import scipy as sp
In [2]:
# Problem 1
x = [0, 1, [2]]
x[2][0] = 3
print(x)
# this should print [0, 1, [3]]
x[2].append(4)
print(x)
# this should print [0, 1, [3, 4]]
x[2] = 2
print(x)
# this should print [0, 1, 2]
In [3]:
# Problem 2
def my_sum(a_list):
the_sum = 0
for n in a_list:
the_sum += n
return the_sum
print(my_sum([1, 2, 3, 4]))
# Problem 3
def str_sum(a_list, separator=" "):
return separator.join(a_list)
print(str_sum(["aa", "bb", "cc"], ""))
In [4]:
# Problem 4
def product(a_list):
""" Using a python list and standard python. """
the_prod = 1
for n in a_list:
the_prod *= n
return the_prod
def np_prod(a_list):
""" Convert python list to numpy and use np for multiplication. """
return np.prod(a_list)
print(product([1, 2, 3]))
print(np_prod([1, 2, 3]))
In [13]:
# Problem 5
def factorial(x):
""" Using standard python and no previous functions. """
fact = 1
for n in range(1, x + 1):
fact *= n
return fact
# def prod_fact(x):
# """ Use the product function from above. """
# return product(range(1, x + 1))
# as lambda function
prod_fact = lambda x: product(range(1, x + 1))
def np_factorial(x):
""" Use numpy to compute the factorial.
per SO at
http://stackoverflow.com/questions/21753841/factorial-in-numpy-and-scipy
numpy.math = scipy.math = math but scipy.misc uses a different function.
"""
import scipy.misc
return scipy.misc.factorial(x)
print(factorial(5))
print(prod_fact(5))
print(np_factorial(5))
Why is the functional version faster by approximately 12%?
In [39]:
import time
start_time = time.time()
from functools import reduce
sqrs = reduce(lambda x, y: x + y,
map(lambda x: x * x, (i for i in range(1, 10**7))))
round(time.time() - start_time, 3)
Out[39]:
In [50]:
import time
start_time = time.time()
sum((i**2 for i in range(1, 10**7)))
round(time.time() - start_time, 3)
Out[50]:
In [52]:
improvement = (1 - 3.967/4.51) * 100
print(round(improvement, 2))