{ "metadata": { "name": "05_other" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Doctest" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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](http://docs.python.org/2/library/doctest.html)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def multiply(a, b):\n", " \"\"\"Return the moltiplication of two values. ::\n", "\n", " Example\n", " --------\n", " \n", " ::\n", "\n", " >>> multiply(1, 2)\n", " 2\n", " >>> multiply(1, 2.)\n", " 2.0\n", " >>> multiply('a', 4)\n", " 'aaaa'\n", " \"\"\"\n", " pass\n", "\n", "import doctest\n", "doctest.run_docstring_examples(multiply, globals(), verbose=True)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Exercise 13" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%bash\n", "python2 bbox.py" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "file, write, open and print" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More info: http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files and http://docs.python.org/2/library/stdtypes.html#file-objects" ] }, { "cell_type": "code", "collapsed": false, "input": [ "#\n", "# generate random data\n", "#\n", "import random\n", "\n", "def get_random(num, upto=100):\n", " \"\"\"Return a list of random numbers:\n", "\n", " >>> get_random(3) # doctest: +ELLIPSIS\n", " [...]\n", " \"\"\"\n", " random_number = []\n", " for _ in xrange(num):\n", " random_number.append(random.random() * upto)\n", " return random_number\n", "\n", "#\n", "# write random data\n", "#\n", "NROWS = 10\n", "NCOLS = 3\n", "\n", "def write_random(rows, cols, filename, upto=100):\n", " # open a file in write mode\n", " data = open(filename, mode='w+')\n", " for row in xrange(rows):\n", " data.write(';'.join([str(num) for num in get_random(cols)]) + '\\n')\n", " data.close()\n", " \n", "write_random(NROWS, NCOLS, 'data.csv')\n", "\n", "#\n", "# read data from file\n", "#\n", "def read(filename):\n", " # open a file in read mode\n", " data = open(filename, mode='r')\n", " for row in data:\n", " print row\n", " data.close()\n", " \n", "read('data.csv')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Exercise 14" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Define a function that using the numpy library, allow user to compute: average, std, min, max [5 min]. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before to start, numpy have several mathematical and statistical functions" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy\n", "\n", "numpy.average([0, 1, 2, 3, 4, 5, 6])" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "def compute_from_file(filename, function, sep=';'):\n", " \"\"\"Do some mathematical operations for each row in a file\n", " \n", " >>> compute_from_file('data.csv', numpy.average)\n", " [...]\n", " >>> compute_from_file('data.csv', numpy.median)\n", " [...]\n", " >>> compute_from_file('data.csv', numpy.min)\n", " \"\"\"\n", " pass" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A possible solution is:" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "os" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import os" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "os.listdir('.')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "LIMIT = 10\n", "count = 0\n", "for f in sorted(os.listdir('.')):\n", " count += 1\n", " if count > LIMIT:\n", " break\n", " if os.path.isfile(f):\n", " print 'is a file: %s' % f\n", " elif os.path.islink(f):\n", " print 'is a link: %s' % f\n", " elif os.path.isdir(f):\n", " print 'is a directory: %s' % f" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "import os\n", "\n", "from take_time import timeit\n", "\n", "class Finder(object):\n", " def __init__(self, dirpath, extension, verbose=False):\n", " self.found = 0\n", " self.analyzed = 0\n", " self.dirpath = dirpath\n", " self.extension = extension\n", " self.verbose = verbose\n", "\n", " @timeit\n", " def __call__(self):\n", " self.looking_for(self.dirpath)\n", " print \"Analyzed: %d filse\\nFound: %d files\" % (self.analyzed, self.found)\n", "\n", " def looking_for(self, dirpath):\n", " for f in sorted(os.listdir(dirpath)):\n", " self.analyzed += 1\n", " abspath = os.path.join(dirpath, f)\n", " if os.path.isfile(abspath):\n", " fname, fext = os.path.splitext(abspath)\n", " if fext == self.extension:\n", " self.found += 1\n", " if self.verbose:\n", " print 'found: %s' % abspath\n", " if os.path.isdir(abspath):\n", " self.looking_for(abspath)\n", "\n", "Finder('solutions/', '.py')()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we need to copy, remove, move directories the right tool is: [shutil](http://docs.python.org/2/library/shutil.html)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from shutil import copytree, ignore_patterns\n", "\n", "copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "fnmatch" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import fnmatch\n", "\n", "for file in os.listdir('.'):\n", " if fnmatch.fnmatch(file, '*.py'):\n", " print file" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Exercise 15" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Modify the Find class using fnmatch. [5 min]" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "numpy" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "even = np.arange(0, 10, 2, dtype=np.float)\n", "even" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "odd = np.arange(1, 10, 2, dtype=np.float)\n", "odd" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "even + odd" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "odd - even" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "even / odd" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "array2d = np.arange(10000).reshape(100,100)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "array2d" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "array2d.T" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "array2d / 2" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And much much more features... start from the [Numpy Tutorial](http://www.scipy.org/Tentative_NumPy_Tutorial)" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "matplotlib" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import matplotlib.pyplot as plt\n", "import numpy as np" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "x = np.arange(0, 2*np.pi, 0.01)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.plot(x, np.sin(x), 'r-', x, np.cos(x), 'b-')\n", "plt.show()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.grid()\n", "plt.plot(x, np.sin(x), 'r-', x, np.cos(x), 'b-')\n", "plt.title(r'Comparison between sin and cos')\n", "plt.xlabel(r'x')\n", "plt.ylabel(r\"y\")\n", "plt.savefig(\"comparison_sin_cos.png\", dpi=200,\n", " format='png', transparent=True, bbox_inches='tight')\n", "plt.show()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.core.display import Image" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "Image(filename=\"comparison_sin_cos.png\") # load the figure that we create with plt.savefig" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }