Often we need both: document our function and test that it's working properly, one of the easiest way to do both is using the doctest.
def multiply(a, b):
"""Return the moltiplication of two values. ::
Example
--------
::
>>> multiply(1, 2)
2
>>> multiply(1, 2.)
2.0
>>> multiply('a', 4)
'aaaa'
"""
pass
import doctest
doctest.run_docstring_examples(multiply, globals(), verbose=True)
Modify the above function to pass all the tests. After that modify the class Bbox contained in bbox.py to pass all the following tests:
%%bash
python2 bbox.py
#
# generate random data
#
import random
def get_random(num, upto=100):
"""Return a list of random numbers:
>>> get_random(3) # doctest: +ELLIPSIS
[...]
"""
random_number = []
for _ in xrange(num):
random_number.append(random.random() * upto)
return random_number
#
# write random data
#
NROWS = 10
NCOLS = 3
def write_random(rows, cols, filename, upto=100):
# open a file in write mode
data = open(filename, mode='w+')
for row in xrange(rows):
data.write(';'.join([str(num) for num in get_random(cols)]) + '\n')
data.close()
write_random(NROWS, NCOLS, 'data.csv')
#
# read data from file
#
def read(filename):
# open a file in read mode
data = open(filename, mode='r')
for row in data:
print row
data.close()
read('data.csv')
Define a function that using the numpy library, allow user to compute: average, std, min, max [5 min].
Before to start, numpy have several mathematical and statistical functions
import numpy
numpy.average([0, 1, 2, 3, 4, 5, 6])
def compute_from_file(filename, function, sep=';'):
"""Do some mathematical operations for each row in a file
>>> compute_from_file('data.csv', numpy.average)
[...]
>>> compute_from_file('data.csv', numpy.median)
[...]
>>> compute_from_file('data.csv', numpy.min)
"""
pass
A possible solution is:
import os
os.listdir('.')
LIMIT = 10
count = 0
for f in sorted(os.listdir('.')):
count += 1
if count > LIMIT:
break
if os.path.isfile(f):
print 'is a file: %s' % f
elif os.path.islink(f):
print 'is a link: %s' % f
elif os.path.isdir(f):
print 'is a directory: %s' % f
import os
from take_time import timeit
class Finder(object):
def __init__(self, dirpath, extension, verbose=False):
self.found = 0
self.analyzed = 0
self.dirpath = dirpath
self.extension = extension
self.verbose = verbose
@timeit
def __call__(self):
self.looking_for(self.dirpath)
print "Analyzed: %d filse\nFound: %d files" % (self.analyzed, self.found)
def looking_for(self, dirpath):
for f in sorted(os.listdir(dirpath)):
self.analyzed += 1
abspath = os.path.join(dirpath, f)
if os.path.isfile(abspath):
fname, fext = os.path.splitext(abspath)
if fext == self.extension:
self.found += 1
if self.verbose:
print 'found: %s' % abspath
if os.path.isdir(abspath):
self.looking_for(abspath)
Finder('solutions/', '.py')()
When we need to copy, remove, move directories the right tool is: shutil
from shutil import copytree, ignore_patterns
copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
import fnmatch
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.py'):
print file
Modify the Find class using fnmatch. [5 min]
import numpy as np
even = np.arange(0, 10, 2, dtype=np.float)
even
odd = np.arange(1, 10, 2, dtype=np.float)
odd
even + odd
odd - even
even / odd
array2d = np.arange(10000).reshape(100,100)
array2d
array2d.T
array2d / 2
And much much more features... start from the Numpy Tutorial
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 2*np.pi, 0.01)
plt.plot(x, np.sin(x), 'r-', x, np.cos(x), 'b-')
plt.show()
plt.grid()
plt.plot(x, np.sin(x), 'r-', x, np.cos(x), 'b-')
plt.title(r'Comparison between sin and cos')
plt.xlabel(r'x')
plt.ylabel(r"y")
plt.savefig("comparison_sin_cos.png", dpi=200,
format='png', transparent=True, bbox_inches='tight')
plt.show()
from IPython.core.display import Image
Image(filename="comparison_sin_cos.png") # load the figure that we create with plt.savefig