Doctest

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.

In [ ]:
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)

Exercise 13

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:

In [ ]:
%%bash
python2 bbox.py

file, write, open and print

In [ ]:
#
# 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')

Exercise 14

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

In [ ]:
import numpy

numpy.average([0, 1, 2, 3, 4, 5, 6])
In [ ]:
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:

In [ ]:
 

os

In [ ]:
import os
In [ ]:
os.listdir('.')
In [ ]:
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
In [ ]:
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

In [ ]:
from shutil import copytree, ignore_patterns

copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

fnmatch

In [ ]:
import fnmatch

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.py'):
        print file

Exercise 15

Modify the Find class using fnmatch. [5 min]

In [ ]:
 

numpy

In [ ]:
import numpy as np
In [ ]:
even = np.arange(0, 10, 2, dtype=np.float)
even
In [ ]:
odd = np.arange(1, 10, 2, dtype=np.float)
odd
In [ ]:
even + odd
In [ ]:
odd - even
In [ ]:
even / odd
In [ ]:
array2d = np.arange(10000).reshape(100,100)
In [ ]:
array2d
In [ ]:
array2d.T
In [ ]:
array2d / 2

And much much more features... start from the Numpy Tutorial

matplotlib

In [ ]:
import matplotlib.pyplot as plt
import numpy as np
In [ ]:
x = np.arange(0, 2*np.pi, 0.01)
In [ ]:
plt.plot(x, np.sin(x), 'r-', x, np.cos(x), 'b-')
plt.show()
In [ ]:
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()
In [ ]:
from IPython.core.display import Image
In [ ]:
Image(filename="comparison_sin_cos.png")  # load the figure that we create with plt.savefig
In [ ]: