commit f71e7e167b637525fe67957a03ed71743e3833c9 Author: cif2cif Date: Mon Feb 1 13:05:58 2016 +0100 First commit notebooks for python diff --git a/python/1_0_Intro_Python.ipynb b/python/1_0_Intro_Python.ipynb new file mode 100644 index 0000000..0a00b21 --- /dev/null +++ b/python/1_0_Intro_Python.ipynb @@ -0,0 +1,124 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Introduction to Python" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This lecture provides a quick introduction to programming in Python as well as the programming environment used in the course." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Table of Contents" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. [Install the environment and Intro to Notebooks](1_1_Notebooks.ipynb)\n", + "2. Intro to Python\n", + " 1. Built-in Types\n", + " 1. [Booleans, numbers and strings](1_2_Numbers_Strings.ipynb)\n", + " 2. [Sequences (lists, tuples and range)](1_3_Sequences.ipynb)\n", + " 3. [Sets (set, frozenset) and Mappings (dictionary)](1_4_Sets.ipynb)\n", + " 2. [Control flow statements](1_5_ControlFlow.ipynb)\n", + " 3. [Functions](1_6_Functions.ipynb)\n", + " 4. [Variables](1_7_Variables.ipynb)\n", + " 5. [Classes](1_8_Classes.ipynb)\n", + " 6. [Errors and Exceptions](1_9_Errors_Exceptions.ipynb)\n", + " 7. [Modules and Packages](1__10_Modules_Packages.ipynb)\n", + " 8. Testing / Generadores / Decoradores" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# References" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* [The Python tutorial](https://docs.python.org/3/tutorial/)\n", + "* [Object-Oriented Programming in Python](http://python-textbok.readthedocs.org/en/latest/index.html)\n", + "* [Python3 tutorial](http://www.python-course.eu/python3_course.php)\n", + "* [Python for the Busy Java Developer, Deepak Sarda, 2014](http://antrix.net/static/pages/python-for-java/online/)\n", + "* [Style Guide for Python Code (PEP-0008)](https://www.python.org/dev/peps/pep-0008/)\n", + "* [Python Slides](http://tdc-www.harvard.edu/Python.pdf)\n", + "* [Python for Programmers - 1 day course](http://www.ucs.cam.ac.uk/docs/course-notes/unix-courses/archived/archived-python-courses/PythonProgIntro/files/notes.pdf)\n", + "* [Dive into Python 3, Mark Pilgrim, 2009](http://www.diveintopython3.net/)\n", + "* [Think Python: How to Think Like a Computer Scientist](http://www.greenteapress.com/thinkpython/html/index.html)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/python/1_1_Notebooks.ipynb b/python/1_1_Notebooks.ipynb new file mode 100644 index 0000000..177fb93 --- /dev/null +++ b/python/1_1_Notebooks.ipynb @@ -0,0 +1,188 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# How to install the environment and play with notebooks" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this lecture we will learn (i) how to set up your environment and (ii) how to run notebooks and use them" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 1. Set up the environment" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. Install Anaconda \n", + "* Download the suitable version for your operating system of Python 3 at https://www.continuum.io/downloads\n", + "* Follow the installation instructions. In Linux/Mac, launch a terminal and execute the installer script.\n", + "2. [Optional, anaconda already installs jupyter] Install Jupyter http://jupyter.readthedocs.org/en/latest/install.html\n", + "* Launch a terminal and execute 'conda install jupyter'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 2. Notebooks in a nutshell" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2.1 Launching jupyter" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. Launch a terminal from the directory you have your notebook (file extension .ipynb) or you want to create your notebook\n", + "1. Write (without '') 'jupyter notebook' and press click" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In case you have not installed the environment, you can run Jupyter here https://try.jupyter.org/" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2.2 Running notebooks" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can create, open or save notebooks from the menu File." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notebooks have two main types of cells: code (executable) and text (called 'markdown'). You can change the type of a cell in the toolbar. A detailed user manual of Jupyter can be found here: \n", + "* http://jupyter.cs.brynmawr.edu/hub/dblank/public/Jupyter%20Notebook%20Users%20Manual.ipynb\n", + "* http://jupyter-notebook.readthedocs.org/en/latest/notebook.html" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For executing a 'code' cell, you can\n", + "* press Shift+Enter\n", + "* click on the 'run cell' button of the toolbar, or \n", + "* select the Cell-Run menu item" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Example: we use Jupyter as a calculator, let's execute 2+2" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "2+2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's try: write 2+2 in the cell below and execute the cell" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3+" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/python/1_2_Numbers_Strings.ipynb b/python/1_2_Numbers_Strings.ipynb new file mode 100644 index 0000000..8094151 --- /dev/null +++ b/python/1_2_Numbers_Strings.ipynb @@ -0,0 +1,1171 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Built-in Types: Booleans, Numbers and Strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Python comes with standard types that are built in the interpreter. \n", + "\n", + "The main built-in types are booleans, numeric, strings and sequences. More details can be found in the [Python documentation](https://docs.python.org/3/library/stdtypes.html)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## 1. Booleans" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 52, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "True and False # operations with booleans" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 53, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "not True" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 54, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "True or False" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Numbers" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In Python3, there are the following [numeric types](https://docs.python.org/3/library/stdtypes.html#typesnumeric):\n", + "* integers (int): 1, -1, ...\n", + "* floating point numbers (float): 0.1, 1E2\n", + "* complex numbers (complex): 2 + 3j\n", + "Let's play a bit" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 + 2 # 2 plus 2 (integers)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "6.0" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2.0 * 3.0 # 2.0 times 3.0 (floats)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "16.0" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2.0 ** 4.0 # 2.0 to the power of 4 (float)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(8+9j)" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "(3 + 4j) + (5 + 5j) #add two complex numbers" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "3.3333333333333335" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "10 / 3 # classic division" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "10 // 3 # floor division" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "10 % 3 # remainder" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "inf" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "10e158*17e158 #overflow shown as 'inf', infinitive" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "int" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(10)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "complex" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(2 + 3j)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "float" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(2.1)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "float" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(2E3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Strings" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Strings are **immutable sequences** of Unicode code points.\n", + "\n", + "Strings in Python can be enclosed in matching single quotes or double quotes." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a string'" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"This is a string\"" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is also a string'" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'This is also a string'" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"This is a string containing single quotes 'hi'\"" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"This is a string containing single quotes 'hi'\"" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is string containing double quotes \"hi\"'" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'This is string containing double quotes \"hi\"'" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is \\n\\na long string\\n\\n'" + ] + }, + "execution_count": 48, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'''This is \n", + "\n", + "a long string\n", + "\n", + "''' # Triple quoted strings are used for long strings that span several lines, \n", + " # We can use triple single quotes or triple double quotes for long strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Strings can contain special characters: \\n (new line), \\t (tab), \\a (beep) and \\\\\\ (slash character)" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'String with special characters: \\n newline, \\x07 beep and \\\\ slash'" + ] + }, + "execution_count": 50, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"String with special characters: \\n newline, \\a beep and \\\\ slash\"" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'concatenate two strings'" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"concatenate \" + \"two strings\" #use of '+' for concatenating two strings" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len('hola') # length of a string" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "str" + ] + }, + "execution_count": 51, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(\"hola\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Strings are sequences, so they can be accessed through and index starting from 0" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "s = \"hola\" # assign the string value \"hola\" to the variable s" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'hola'" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s # get the value of s" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'h'" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'o'" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[1]" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'a'" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[3]" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'a'" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s [-1] # we can start from the beginning (index 0, 1, 2, ...) or from the last position (-1, -2, ...)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since Strings are sequences, they can be accessed with the *slice notation*: s[start:end]. The resulting slice includes the elements of the sequence from position start (included) to position end (excluded). Both arguments start and end are optional (default values: start->0, end->length)." + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'ho'" + ] + }, + "execution_count": 56, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[0:2] #slice [0,2)" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'ho'" + ] + }, + "execution_count": 57, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[:2] #slice [0,2)" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'hola'" + ] + }, + "execution_count": 58, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[:] #slice [0, len(s)]" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'ho'" + ] + }, + "execution_count": 59, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[:-2]" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'ho'" + ] + }, + "execution_count": 61, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[-4:-2]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since Python 1.4, you can use the extended slice notation: [start:end:step]. The slice moves from start before end is reached, and moves from one position to the next by step items.\n", + "\n", + "Step cannot be 0.\n", + "\n", + "If start or end are omitted, they become the end value (the end side depends on the sing of step). This means, for a positive step, default start and end are [0,len), while for a negative step, the default values are [len, 0)" + ] + }, + { + "cell_type": "code", + "execution_count": 72, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "se = \"This is a string\"" + ] + }, + { + "cell_type": "code", + "execution_count": 73, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a string'" + ] + }, + "execution_count": 73, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "se[::1] # moves from 0 to len, and the index is incremented by 1" + ] + }, + { + "cell_type": "code", + "execution_count": 80, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Ti sasr'" + ] + }, + "execution_count": 80, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "se[0:14:2] #take the even indexed characters from 0 to 14" + ] + }, + { + "cell_type": "code", + "execution_count": 93, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'gnirts a si sihT'" + ] + }, + "execution_count": 93, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "se[::-1] #reverse the string" + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'gnirts a si'" + ] + }, + "execution_count": 92, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "se[:4:-1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use also operations (+, *) with strings" + ] + }, + { + "cell_type": "code", + "execution_count": 97, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "a = 'b'" + ] + }, + { + "cell_type": "code", + "execution_count": 101, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a string plus This is a string plus bbb'" + ] + }, + "execution_count": 101, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "se + \" plus \" + se + \" plus \"+ a*3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also used methods for Strings, such as lower(), upper(), split(), ...\n", + "\n", + "You can check the available methods by writing a String variable, \".\", and pressing Tab." + ] + }, + { + "cell_type": "code", + "execution_count": 102, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'hola'" + ] + }, + "execution_count": 102, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s.lower()" + ] + }, + { + "cell_type": "code", + "execution_count": 103, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'HOLA'" + ] + }, + "execution_count": 103, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s.upper()" + ] + }, + { + "cell_type": "code", + "execution_count": 106, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['h', 'la']" + ] + }, + "execution_count": 106, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s.split('o') # splits String " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercises" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Think if the following expressions are ok, and which will be the result.\n", + "\n", + "Execute the cells and check your answers." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "\"hohoho\".split('h')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "type(\"hohoho\".split('h'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3+" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/python/1_3_Sequences.ipynb b/python/1_3_Sequences.ipynb new file mode 100644 index 0000000..e2cf863 --- /dev/null +++ b/python/1_3_Sequences.ipynb @@ -0,0 +1,1105 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Built-in Types: Sequences" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Sequences** are ordered collections of elements. The basic built-int sequence types are **lists**, **tuples** and **range** objets. There other sequence types for text strings (str, Strings) or binary data.\n", + "\n", + "Sequences can be mutable or inmutable, if their value can be changed or not, respectively.\n", + "* **lists** are mutable ordered sequences of values\n", + "* **tuples** are inmutable ordered sequences of values\n", + "* **ranges** are immutable sequences of numbers" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## 1. Lists" + ] + }, + { + "cell_type": "code", + "execution_count": 137, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "l = [1, 2, 3, 4, 5, 6]" + ] + }, + { + "cell_type": "code", + "execution_count": 138, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6]" + ] + }, + "execution_count": 138, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l" + ] + }, + { + "cell_type": "code", + "execution_count": 139, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3]" + ] + }, + "execution_count": 139, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l[0:3] # we can use slicing in sequence types" + ] + }, + { + "cell_type": "code", + "execution_count": 140, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "other_list = [1, 0.0, \"hola\"] #lists can have elements of different types" + ] + }, + { + "cell_type": "code", + "execution_count": 141, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 0.0, 'hola']" + ] + }, + "execution_count": 141, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "other_list" + ] + }, + { + "cell_type": "code", + "execution_count": 142, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 1, 0.0, 'hola']" + ] + }, + "execution_count": 142, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l + other_list # we can add lists (append)" + ] + }, + { + "cell_type": "code", + "execution_count": 143, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]" + ] + }, + "execution_count": 143, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l * 3 # we can add n times a list" + ] + }, + { + "cell_type": "code", + "execution_count": 144, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "6" + ] + }, + "execution_count": 144, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len(l) # length of a list (as Strings)" + ] + }, + { + "cell_type": "code", + "execution_count": 145, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "l.append(7) #append at the end of the list. Check help with Shift-tab, and methods with tab" + ] + }, + { + "cell_type": "code", + "execution_count": 146, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7]" + ] + }, + "execution_count": 146, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l" + ] + }, + { + "cell_type": "code", + "execution_count": 147, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "7" + ] + }, + "execution_count": 147, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l.pop() # remove last element" + ] + }, + { + "cell_type": "code", + "execution_count": 148, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6]" + ] + }, + "execution_count": 148, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l" + ] + }, + { + "cell_type": "code", + "execution_count": 149, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 149, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l.pop(2) # remove element at index 2" + ] + }, + { + "cell_type": "code", + "execution_count": 150, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 4, 5, 6]" + ] + }, + "execution_count": 150, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 151, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "l.insert(2,3) # insert at index 2 the value 3" + ] + }, + { + "cell_type": "code", + "execution_count": 152, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6]" + ] + }, + "execution_count": 152, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l" + ] + }, + { + "cell_type": "code", + "execution_count": 153, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "l.reverse()" + ] + }, + { + "cell_type": "code", + "execution_count": 154, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[6, 5, 4, 3, 2, 1]" + ] + }, + "execution_count": 154, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l" + ] + }, + { + "cell_type": "code", + "execution_count": 155, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "l.sort()" + ] + }, + { + "cell_type": "code", + "execution_count": 156, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6]" + ] + }, + "execution_count": 156, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l" + ] + }, + { + "cell_type": "code", + "execution_count": 157, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "l.remove(3) # remove first ocurrence of 3 from l. Remember: remove (element) vs pop(index)" + ] + }, + { + "cell_type": "code", + "execution_count": 158, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 4, 5, 6]" + ] + }, + "execution_count": 158, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l" + ] + }, + { + "cell_type": "code", + "execution_count": 159, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "l[0] = 0 # lists are mutable" + ] + }, + { + "cell_type": "code", + "execution_count": 160, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 5, 6]" + ] + }, + "execution_count": 160, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l" + ] + }, + { + "cell_type": "code", + "execution_count": 161, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 161, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 in l # check if an element is in a list" + ] + }, + { + "cell_type": "code", + "execution_count": 162, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 162, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "7 in l # check if an element is in a list " + ] + }, + { + "cell_type": "code", + "execution_count": 163, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 163, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "4 not in l # check if an element is not in a list" + ] + }, + { + "cell_type": "code", + "execution_count": 164, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 164, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l.index(4) # search for an item" + ] + }, + { + "cell_type": "code", + "execution_count": 165, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "ValueError", + "evalue": "-1 is not in list", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ml\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# search for an item, error since it is not in the list\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mValueError\u001b[0m: -1 is not in list" + ] + } + ], + "source": [ + "l.index(-1) # search for an item, error since it is not in the list" + ] + }, + { + "cell_type": "code", + "execution_count": 166, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "matrix = [[1,2], [3,4]] # matrix" + ] + }, + { + "cell_type": "code", + "execution_count": 167, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[[1, 2], [3, 4]]" + ] + }, + "execution_count": 167, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "matrix" + ] + }, + { + "cell_type": "code", + "execution_count": 168, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 168, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "matrix[0][0]" + ] + }, + { + "cell_type": "code", + "execution_count": 169, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 169, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "matrix[0][1]" + ] + }, + { + "cell_type": "code", + "execution_count": 170, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "list" + ] + }, + "execution_count": 170, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(matrix)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Tuples" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Tuples are *inmutable* sequences, tipically used to store collections of heterogeneous data.\n", + "\n", + "The main difference from lists is that lists are *mutable* while tuples are *inmutable*. Thus, tuples have not methods such as insert(), pop(), remove() or append() to change them.\n", + "\n", + "Tuples are faster than lists. Its main usage is when the collection is constant, or you do not want it can be changed (write protected). \n", + "\n", + "Tuples can be converted into lists and vice-versa, with the methods list() and tuple()." + ] + }, + { + "cell_type": "code", + "execution_count": 171, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "tuple = ('a', 1)" + ] + }, + { + "cell_type": "code", + "execution_count": 172, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "('a', 1)" + ] + }, + "execution_count": 172, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "tuple" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false + }, + "source": [ + "Tuples implement all the common [sequence operators](https://docs.python.org/3/library/stdtypes.html#typesseq-common), such as slicing, concatenation, len, etc." + ] + }, + { + "cell_type": "code", + "execution_count": 173, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(1, 'a')" + ] + }, + "execution_count": 173, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "tuple[::-1]" + ] + }, + { + "cell_type": "code", + "execution_count": 174, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 174, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len(tuple)" + ] + }, + { + "cell_type": "code", + "execution_count": 175, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "('a', 1, 'a', 1, 'b', 'c', 2.1, True)" + ] + }, + "execution_count": 175, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "tuple * 2 + ('b', 'c', 2.1, True)" + ] + }, + { + "cell_type": "code", + "execution_count": 176, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 176, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "tuple[1]" + ] + }, + { + "cell_type": "code", + "execution_count": 177, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "'tuple' object does not support item assignment", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mtuple\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m2\u001b[0m \u001b[1;31m# Error, tuples are inmutable\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" + ] + } + ], + "source": [ + "tuple[1] = 2 # Error, tuples are inmutable" + ] + }, + { + "cell_type": "code", + "execution_count": 178, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "tuple" + ] + }, + "execution_count": 178, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(tuple)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Range" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "A [range](https://docs.python.org/3/library/stdtypes.html#range) represents an immutable sequence of numbers. Ranges are created with two constructors: *range(stop)* or *range(start, stop, [step])*. \n", + "\n", + "The default *start* is 0 and the default *step* is 1. It generates a sequence [start, stop)" + ] + }, + { + "cell_type": "code", + "execution_count": 179, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "r = range(10)" + ] + }, + { + "cell_type": "code", + "execution_count": 180, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "range(0, 10)" + ] + }, + "execution_count": 180, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "r" + ] + }, + { + "cell_type": "code", + "execution_count": 181, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 181, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "5 in r # check if a number is in a range" + ] + }, + { + "cell_type": "code", + "execution_count": 182, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 182, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "r[2] # Get a value" + ] + }, + { + "cell_type": "code", + "execution_count": 183, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "range" + ] + }, + "execution_count": 183, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(r)" + ] + }, + { + "cell_type": "code", + "execution_count": 184, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" + ] + }, + "execution_count": 184, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(range(10))" + ] + }, + { + "cell_type": "code", + "execution_count": 185, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 3, 5, 7, 9]" + ] + }, + "execution_count": 185, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(range(1,10,2))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3+" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/python/1_4_Sets.ipynb b/python/1_4_Sets.ipynb new file mode 100644 index 0000000..91093dc --- /dev/null +++ b/python/1_4_Sets.ipynb @@ -0,0 +1,624 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Built-in Types: Sets and Mappings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* *Sets* are unordered bags of values\n", + "* *Dictionaries* are unordered bags of key-values pairs\n", + "\n", + "A set object is an unordered collection of distinct objects. There are two built-in set types: **set** (mutable) and **frozenset** (inmutable).\n", + "\n", + "A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is only one bultin mapping type: **dictionary**." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## 1. Sets" + ] + }, + { + "cell_type": "code", + "execution_count": 413, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "set()" + ] + }, + "execution_count": 413, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_set = set() #create a set\n", + "my_set" + ] + }, + { + "cell_type": "code", + "execution_count": 414, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{1}" + ] + }, + "execution_count": 414, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_set.add(1) # add an element\n", + "my_set" + ] + }, + { + "cell_type": "code", + "execution_count": 415, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "my_set.add(2) # add another element" + ] + }, + { + "cell_type": "code", + "execution_count": 416, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2}" + ] + }, + "execution_count": 416, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_set" + ] + }, + { + "cell_type": "code", + "execution_count": 417, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2, 3}" + ] + }, + "execution_count": 417, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_set.add(3) # add another one\n", + "my_set" + ] + }, + { + "cell_type": "code", + "execution_count": 418, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2, 3}" + ] + }, + "execution_count": 418, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_set.add(1) #try to add a repeated element\n", + "my_set" + ] + }, + { + "cell_type": "code", + "execution_count": 419, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}" + ] + }, + "execution_count": 419, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s2 = set(range(10)) # we can create a set from a range\n", + "s2" + ] + }, + { + "cell_type": "code", + "execution_count": 420, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "l = ['a', 'a', 'b', 'c', 'c', 'c']" + ] + }, + { + "cell_type": "code", + "execution_count": 421, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{'a', 'b', 'c'}" + ] + }, + "execution_count": 421, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s3 = set(l) # if we create a set from a list, elements are not repeated\n", + "s3" + ] + }, + { + "cell_type": "code", + "execution_count": 422, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 422, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len(s3) " + ] + }, + { + "cell_type": "code", + "execution_count": 423, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{0, 1, 2, 3, 4, 5, 'c', 6, 7, 8, 9, 'a', 'b'}" + ] + }, + "execution_count": 423, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s3.union(s2) # we can use set methods: union(), intersection(), difference(), ..." + ] + }, + { + "cell_type": "code", + "execution_count": 424, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 424, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "3 in my_set #check membership" + ] + }, + { + "cell_type": "code", + "execution_count": 425, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "set" + ] + }, + "execution_count": 425, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(s3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Dictionaries" + ] + }, + { + "cell_type": "code", + "execution_count": 426, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{'key1': 1, 'key2': 2, 'key3': 3}" + ] + }, + "execution_count": 426, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dictionary = {'key1': 1, 'key2': 2, 'key3': 3} # pairs of key-value mappings\n", + "my_dictionary" + ] + }, + { + "cell_type": "code", + "execution_count": 427, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 427, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dictionary['key1'] #retrieve a value given a key" + ] + }, + { + "cell_type": "code", + "execution_count": 428, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{'key1': 1, 'key2': 2, 'key3': 3}" + ] + }, + "execution_count": 428, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dict = dict()\n", + "my_dict['key1'] = 1\n", + "my_dict['key2'] = 2\n", + "my_dict['key3'] = 3\n", + "my_dict # alternative way to create a dictionary " + ] + }, + { + "cell_type": "code", + "execution_count": 429, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 429, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dict == my_dictionary # check if both dictionaries are equal" + ] + }, + { + "cell_type": "code", + "execution_count": 430, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{'one': {'two': {'three': 'Nested dict'}}}" + ] + }, + "execution_count": 430, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dict2 = {'one': {'two': {'three': 'Nested dict'}}} #nested dictionary\n", + "my_dict2" + ] + }, + { + "cell_type": "code", + "execution_count": 431, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Nested dict'" + ] + }, + "execution_count": 431, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dict2['one']['two']['three'] #access the value" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false + }, + "source": [ + "Dictionaries have different methods, check them with Tab." + ] + }, + { + "cell_type": "code", + "execution_count": 473, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['key2', 'key3', 'key1'])" + ] + }, + "execution_count": 473, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dict.keys() # in Python3 we get a View object that changes when the dictionary changes" + ] + }, + { + "cell_type": "code", + "execution_count": 478, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['key2', 'key3', 'key1']" + ] + }, + "execution_count": 478, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(my_dict.keys()) # we can convert it to a list, we see dicionaries are unordered" + ] + }, + { + "cell_type": "code", + "execution_count": 474, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_values([2, 3, 1])" + ] + }, + "execution_count": 474, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dict.values()" + ] + }, + { + "cell_type": "code", + "execution_count": 476, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 3, 1]" + ] + }, + "execution_count": 476, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(my_dict.values())" + ] + }, + { + "cell_type": "code", + "execution_count": 479, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "dict" + ] + }, + "execution_count": 479, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(my_dict)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3+" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/python/1_5_ControlFlow.ipynb b/python/1_5_ControlFlow.ipynb new file mode 100644 index 0000000..b3187f0 --- /dev/null +++ b/python/1_5_ControlFlow.ipynb @@ -0,0 +1,698 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Control Flow statements" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Python ends a statement with a colon (:) and blocks are denoted by the level of indentation. " + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Example in Java:\n", + "\n", + "if (a < c) {\n", + " a++;\n", + " b++;\n", + "}\n" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Example in Python: (observe: no parenthesis (), no ending semicolons (;) but a colon is used (:)\n", + "if a < c:\n", + " a++\n", + " b++" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## 1. Conditional statements: if, elif, else" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import random # import random before using it\n", + "x = random.randrange(1, 10) # generate a random integer between [1, 10] (both included)\n", + "x" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Too small\n" + ] + } + ], + "source": [ + "# Execute several times in order the previous cell and this one\n", + "if x < 5:\n", + " print(\"Too small\")\n", + "elif x == 5:\n", + " print(\"Just in the middle\")\n", + "else: \n", + " print(\"Too big\")" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Too small\n" + ] + } + ], + "source": [ + "# Only one branch\n", + "if x <= 5:\n", + " print(\"Too small\")\n", + "else:\n", + " print(\"Too big\")" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Too big\n" + ] + } + ], + "source": [ + "# Python has no switch statement for multiple branches\n", + "if x <= 4:\n", + " print(\"Too small\")\n", + "elif x <= 5:\n", + " print(\"Small\")\n", + "elif x <= 7:\n", + " print (\"Big\")\n", + "else:\n", + " print(\"Too big\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Loops: for, while" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2.1. For" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n" + ] + } + ], + "source": [ + "# for with ranges\n", + "for i in range(10): \n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n" + ] + } + ], + "source": [ + "# for with lists\n", + "l = [1, 2, 3, 4]\n", + "for i in l:\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "a\n", + "b\n" + ] + } + ], + "source": [ + "# for with tuples\n", + "t = (1, 'a', 'b')\n", + "for i in t:\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "k2\n", + "k1\n", + "k3\n" + ] + } + ], + "source": [ + "# for with dictionaries\n", + "d = {'k1':'v1', 'k2':'v2', 'k3':'v3'}\n", + "for i in d:\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "k2 v2\n", + "k1 v1\n", + "k3 v3\n" + ] + } + ], + "source": [ + "# We get only the keys. If we want the pairs we need to create a generator (we will see this later)\n", + "for k,v in d.items():\n", + " print(k, v)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2.2. While" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5\n", + "4\n", + "3\n", + "2\n" + ] + } + ], + "source": [ + "x = 5\n", + "while x > 1:\n", + " print(x)\n", + " x -= 1 # Python does not have x--" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "3\n", + "4\n" + ] + } + ], + "source": [ + "# Else is optional\n", + "x = 2\n", + "while x < 5: \n", + " print(x)\n", + " x += 1" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false + }, + "source": [ + "### 2.3. Break, continue, pass\n", + "\n", + "* **break**: break out of the smallest enclosing loop (for or while)\n", + "* **continue**: continue with the next iteration of the loop\n", + "* **pass**: do nothing\n", + "\n", + "Both *for* and *while* can include an optional statement else which is executed always unless a break statement is reached" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Goal found at index c\n", + "End loop\n" + ] + } + ], + "source": [ + "# Example find an element, else executed at the end\n", + "list = ['a', 'b', 'c']\n", + "goal = 'c'\n", + "for i in list:\n", + " if i == goal:\n", + " print('Goal found at index', i)\n", + "else:\n", + " print('End loop')" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "End loop\n" + ] + } + ], + "source": [ + "# Example else\n", + "list = []\n", + "goal = 'c'\n", + "for i in list:\n", + " if i == goal:\n", + " print('Goal found at index', i)\n", + "else:\n", + " print('End loop')" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Goal found at index c\n" + ] + } + ], + "source": [ + "# We improve above code with break\n", + "# Example else\n", + "list = ['a', 'b', 'c']\n", + "goal = 'c'\n", + "for i in list:\n", + " if i == goal:\n", + " print('Goal found at index', i)\n", + " break\n", + "else:\n", + " print('Goal not found')" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Goal not found\n" + ] + } + ], + "source": [ + "# We improve above code with break\n", + "# Example else\n", + "list = ['a', 'b', 'c']\n", + "goal = 'e'\n", + "for i in list:\n", + " if i == goal:\n", + " print('Goal found at index', i)\n", + " break\n", + "else:\n", + " print('Goal not found')" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "4\n", + "5\n", + "7\n", + "8\n", + "10\n", + "11\n", + "13\n", + "14\n" + ] + } + ], + "source": [ + "# Print numbers from 0 to 15 which are not multiple of 3\n", + "for i in range(15):\n", + " if i % 3 == 0:\n", + " continue\n", + " print(i)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found 4\n" + ] + } + ], + "source": [ + "# Find the first occurrence of an element in a list\n", + "l = [1, 2, 3, 4, 1, 2]\n", + "goal = 4\n", + "for n in l:\n", + " if n == 4:\n", + " print(\"Found\", n)\n", + " break\n", + "else:\n", + " print(\"Not found\")" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Big\n" + ] + } + ], + "source": [ + "# Example of pass, when we do not want to do anything\n", + "x = 4\n", + "if x < 2:\n", + " print(\"Low\")\n", + "elif x >= 2:\n", + " print(\"Big\")\n", + "else:\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. List comprehension\n", + "\n", + "List comprehension are a simple way to create lists like we describe vectors in mathematics.\n", + "\n", + "S = {x² : x in {0 ... 9}}\n", + "\n", + "M = {x | x in S and x even}" + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" + ] + }, + "execution_count": 71, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Syntax: first what we want to include in the list (x) and then how to obtain x\n", + "# list = {x : x in {0 ... 9}}\n", + "list = [x for x in range(10)]\n", + "list" + ] + }, + { + "cell_type": "code", + "execution_count": 70, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" + ] + }, + "execution_count": 70, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# list = {x² : x in {0 ... 9}}\n", + "list = [x*x for x in range(10)]\n", + "list" + ] + }, + { + "cell_type": "code", + "execution_count": 72, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 4, 16, 36, 64]" + ] + }, + "execution_count": 72, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# list = {x² : x in {0 ... 9}, x is even}\n", + "list = [x*x for x in range(10) if x % 2 == 0]\n", + "list" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/python/1_6_Functions.ipynb b/python/1_6_Functions.ipynb new file mode 100644 index 0000000..8b03161 --- /dev/null +++ b/python/1_6_Functions.ipynb @@ -0,0 +1,490 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Functions" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A function is a sequence of statements which performs some kind of task.\n", + "\n", + "They have optional parameters and an optional return value. If no return is provided, the default return value is *NoneType*.\n", + "\n", + "In Python we cannot overload a function. Functions are just names (variables) and cannot have two implementations at the same time. If you declare twice a function, the second declaration overrides the first one. Nevertheless, we can declare default values or variable arguments, which are the main use of overloading." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5\n" + ] + } + ], + "source": [ + "def sum(a, b):\n", + " return a + b\n", + "c = sum(2,3)\n", + "print(c)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5\n" + ] + } + ], + "source": [ + "#keyword parameters\n", + "d = sum(a=2, b=3)\n", + "print(d)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "***\n", + "hi\n", + "***\n" + ] + } + ], + "source": [ + "def greetings():\n", + " print('***')\n", + " print('hi')\n", + " print('***')\n", + "\n", + "greetings()" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "***\n", + "hi\n", + "***\n" + ] + } + ], + "source": [ + "# We can assign a function to a variable. Fun\n", + "d = greetings()" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "NoneType" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(d)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "function" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(greetings)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Function documentation\n", + "The first statement in the body of a function is usually a documentation triple-quoted string, called *docstring*, which can be accessed with function_name.\\__doc__. " + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[3, 2, 1]\n", + "Receives a list and returns the list in reverse order\n" + ] + } + ], + "source": [ + "def reverse(l):\n", + " \"\"\"Receives a list and returns the list in reverse order\"\"\"\n", + " return l[::-1]\n", + "\n", + "l = [1, 2, 3]\n", + "d = reverse(l)\n", + "print(d)\n", + "print(reverse.__doc__)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Default parameters\n", + "\n", + "We can define default parameters by assigning a value to a parameter in the function definition" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "5\n" + ] + } + ], + "source": [ + "def sum(a, b=0):\n", + " return a + b\n", + "print(sum(2))\n", + "print(sum(2,3))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Variable number of arguments" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "6\n" + ] + } + ], + "source": [ + "#variable number of arguments: *\n", + "def sum(a, *l):\n", + " \"\"\"Sum of a non empty list of arbitrary numbers\"\"\"\n", + " total = a\n", + " for num in l:\n", + " total += num\n", + " return total\n", + "print(sum(1))\n", + "print(sum(1,2,3))" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "7\n", + "13\n" + ] + } + ], + "source": [ + "#Packing \n", + "l = [1, 2, 3]\n", + "print(sum(1, *l)) # same than sum(1, 1, 2, 3)\n", + "\n", + "t = (4, 4, 4)\n", + "print(sum(1, *t))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Lambda functions\n", + "\n", + "Lambda functions are anonymous functions. They are used as mini-functions with abbreviated syntax" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "c 27\n", + "c 27\n" + ] + } + ], + "source": [ + "def sq(x):\n", + " return x**x\n", + "c = sq(3)\n", + "print('c', c)\n", + "\n", + "# lambda equivalent\n", + "sq = lambda x : x**x\n", + "c = sq(3)\n", + "print('c', c)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Formatted output: print\n", + "\n", + "\n", + "The arguments of the print function are the following ones:\n", + "\n", + "**print(value1, ..., sep='  ', end='\\n')**\n", + "\n", + "* it can receive a variable number of arguments (value1, value2, ...)\n", + "* *sep*: separator of values (default: ' ')\n", + "* *end*: final character (default: new line)\n", + "\n", + "In Python2, print was not a function, it was a statement, so it was used without parameters: \n", + "\n", + "print x\n", + "\n", + "If you want to use the print syntax in Python2, you can import the print function to make it compatible with Python3: \n", + "\n", + "from \\__future\\__ import print_fuction " + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 2 3 4\n", + "1,2,3,4\n", + "1,2,3,4#1|2|3|4\n" + ] + } + ], + "source": [ + "print(1, 2, 3, 4)\n", + "print(1, 2, 3, 4, sep=',')\n", + "print(1, 2, 3, 4, sep=',', end=\"#\")\n", + "print(1, 2, 3, 4, sep='|')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use [**format**](https://pyformat.info/) for string formatting." + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number: 1,2\n", + "PI #3.141592653589793#\n", + "PI # 3.14#\n" + ] + } + ], + "source": [ + "import math\n", + "print('Number: {},{}'.format(1, 2)) #replaces [] inside the string by the arguments of format\n", + "print('PI #{}#'.format(math.pi))\n", + "print('PI #{:5.2f}#'.format(math.pi)) # at least 5 characters with two decimals" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Input: input\n", + "\n", + "User input can be collected with **input**." + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter a number 5\n", + "5\n" + ] + } + ], + "source": [ + "num = input('Enter a number ')\n", + "print(num)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/python/1_7_Variables.ipynb b/python/1_7_Variables.ipynb new file mode 100644 index 0000000..4f95565 --- /dev/null +++ b/python/1_7_Variables.ipynb @@ -0,0 +1,330 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Variables" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Strongly typed and dynamically typed" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As we have seen previously, in Python we can assign an object to a variable with the assignment operator (=).\n", + "\n", + "Binding a variable in Python means setting a name to hold a reference to some object. Assignment creates references, not copies.\n", + "\n", + "Names in Python do not have an intrinsic type. Objects have types. Python determines the type of the reference automatically based on the data object assigned to it.\n", + "\n", + "In Python, everything is an object, there no difference between primitive types, functions and objects: all are objects." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "a = 2\n", + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Python is a **strongly typed** language and **dynamically typed** language.\n", + "\n", + "This means:\n", + "* ** dynamically typed**: variables do not declare a static type (as in Java int a = 2;). Variables have no type themselves, they are just names that hold a reference to some object. The type of the variable is changed dynamically when you change the type of the assigned data object. \n", + "* **strongly typed**: the interpreter tracks variable types. There is no explicit type conversion. For example, in Javascript we can " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "type(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercises" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Can we assign a String value to the variable a? \n", + "Can we assign the expression 'd' + 3 to the variable a?\n", + "\n", + "\n", + "Give reasons for your answers and check them below." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "a = 'd'\n", + "a" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "a = 'd' + 3\n", + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## 2. Mutability" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false + }, + "source": [ + "Objects whose value can change are said to be **mutable**; objects whose value is unchangeable once they are created are called **immutable**.\n", + "\n", + "* **Mutable types**: integers, floats, strings, tuples\n", + "* **Inmutable types**: lists, dictionaries" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Exercise mutable type\n", + "a = 10\n", + "b = a\n", + "b = 5\n", + "print('a', a)\n", + "print('b', b)\n", + "\n", + "# Which will be the values of a and b?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Exercise mutable type\n", + "a = 10\n", + "a = 10 + 1\n", + "print(a)\n", + "\n", + "# Can we change 'a' if it is inmutable?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Exercise mutable type\n", + "a = \"Hola\"\n", + "b = a\n", + "b = \"Hi\"\n", + "print('a', a)\n", + "print('b', b)\n", + "\n", + "# Which will be the values of a and b?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Exercise inmutable type\n", + "a = [1, 2, 3]\n", + "b = a\n", + "a.append(4)\n", + "print('a', a)\n", + "print('b', b)\n", + "\n", + "# Which will be the value " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Scope" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Example of a local variable\n", + "# The scope defines the visibility of a name within a block. \n", + "# If a local variable is defined in a block, its scope includes that block. \n", + "\n", + "c = 3\n", + "def add(a, b):\n", + " c = a + b\n", + " return c\n", + "d = add(2, 2)\n", + "print('d', d)\n", + "print('c', c)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Access global variables\n", + "\n", + "c = 3\n", + "def add(a, b):\n", + " global c\n", + " c = a + b\n", + " return c\n", + "d = add(2, 2)\n", + "print('d', d)\n", + "print('c', c)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Constants\n", + "\n", + "In Python there is no way to specify that a variable is constant, but there is the convention to write their names in all caps, with underscores separating words." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "NUMBER_OF_LIFES = 5\n", + "\n", + "print(NUMBER_OF_LIFES)\n", + "\n", + "# built-in constants usually do no follow the convention \n", + "import math\n", + "print(math.pi)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/python/1_8_Classes.ipynb b/python/1_8_Classes.ipynb new file mode 100644 index 0000000..b20323c --- /dev/null +++ b/python/1_8_Classes.ipynb @@ -0,0 +1,345 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Classes\n", + "\n", + "In Python everthing is an object. Classes allow programmers to define their own object types.\n", + "\n", + "Classes are defined with the **class** reserved keyword." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Instance attributes and methods\n", + "\n", + "The first argument of instance class method is self, that refers to the current instance of the class.\n", + "There is a special method, __init__ that initializes the object. It is like a constructor, but the object is already created when __init__ is called.\n", + "\n", + "Instance attributes are define as self.variables. (self is the same than this in Java)." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "#Example class declaration\n", + "class TV_Set:\n", + " def __init__(self, name):\n", + " self.name = name\n", + " self.status = 'off'\n", + "\n", + " def on(self):\n", + " self.status = 'on'\n", + "\n", + " def off(self):\n", + " self.status = 'off'" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "<__main__.TV_Set object at 0x7fa0ec1a6c50> off\n" + ] + }, + { + "data": { + "text/plain": [ + "__main__.TV_Set" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#€xample object instantiation\n", + "\n", + "my_tv = TV_Set('Samsung')\n", + "print(my_tv, my_tv.status)\n", + "type(my_tv)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Class attributes\n", + "We can also define class variables and class methods. \n", + "\n", + "Class variables are shared across all class instances. Class methods are called directly in the class. (In Java, this was defined with the keyword static)." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n" + ] + } + ], + "source": [ + "#Example class declaration\n", + "class TV_Set:\n", + " num_tvs = 0\n", + " def __init__(self, name):\n", + " self.name = name\n", + " self.status = 'off'\n", + " TV_Set.num_tvs += 1\n", + "\n", + " def on(self):\n", + " self.status = 'on'\n", + "\n", + " def off(self):\n", + " self.status = 'off'\n", + "\n", + "print(TV_Set.num_tvs)\n", + "\n", + "tv_1 = TV_Set('LG')\n", + "print(TV_Set.num_tvs)\n", + "\n", + "tv_2 = TV_Set('Samsung')\n", + "print(TV_Set.num_tvs)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Special or Magic methods\n", + "\n", + "[Special methods](https://docs.python.org/2/reference/datamodel.html#specialnames) allow programmers to customize a class. The convention for special methods is \\__method\\__.\n", + "\n", + "We have already seen a special method: \\__init\\__. Other special methods are \\__str\\__ (self) for printing) or \\__eq\\__(self, other) for comparing if two objects are equal." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "<__main__.Person object at 0x7fa0ec14ec88>\n" + ] + } + ], + "source": [ + "class Person:\n", + " def __init__(self, name, age):\n", + " self.name = name\n", + " self.age = age\n", + " \n", + "p = Person('Pedro', 10)\n", + "p.age = 0\n", + "print(p)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "name: Pedro, age: 0\n" + ] + } + ], + "source": [ + "# Example __str(self)__\n", + "\n", + "class Person:\n", + " def __init__(self, name, age):\n", + " self.name = name\n", + " self.age = age\n", + " \n", + " def __str__(self):\n", + " return 'name: ' + self.name + ', ' + 'age: ' + str(self.age) # str() for converting int into string\n", + " \n", + "p = Person('Pedro', 10)\n", + "p.age = 0\n", + "print(p)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Private attributes and methods\n", + "\n", + "In Python, all methods and attributes are public. However, Python uses the following conventions\n", + "\n", + "* **Names prefixed by a single leading underscore**: (e.g. self._a, _\\_calculate()): private use. The statement import does not import objects whose name starts with an underscore. In fact, for class inheritance it has the semantics of *protected* (the subclass would have access to the method / attribute).\n", + "\n", + "* **Names prefixed by a double leading underscore** (e.g. \\_\\_calculate(), self.\\_\\_boo): used to avoid a method to be overridden by a subclass. The interpreter invokes name mangling, (inside class FooBar, \\_\\_boo becomes _FooBar\\__boo). This is not used as widely as a single leading underscore." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Instead of Getters and Setters, Python uses Properties" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "name: Pedro, age: -1\n" + ] + } + ], + "source": [ + "# Now we could change the age of Pedro to a negative value\n", + "p.age = -1\n", + "print(p)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In Java, we would define age as private, and getters and setters. In Python, we can use **properties** when we want to control how they are accessed, without changing the interface." + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "name: Pedro, age: 0\n" + ] + } + ], + "source": [ + "class Person:\n", + " def __init__(self, name, age):\n", + " self.name = name\n", + " self.age = age\n", + " \n", + " def __str__(self):\n", + " return 'name: ' + self.name + ', ' + 'age: ' + str(self.age) # str() for converting int into string\n", + " \n", + " @property # property for getter, in this case it is not needed\n", + " def age(self):\n", + " return self._age \n", + " \n", + " @age.setter\n", + " def age(self, val):\n", + " if (val < 0):\n", + " self._age = 0 # A better alternative would be to throw an exception: raise ValueError(\"Age < 0\")\n", + " else:\n", + " self._age = val\n", + " \n", + "p = Person('Pedro', -1)\n", + "print(p)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/python/1_9_Errors_Exceptions.ipynb b/python/1_9_Errors_Exceptions.ipynb new file mode 100644 index 0000000..1329fa3 --- /dev/null +++ b/python/1_9_Errors_Exceptions.ipynb @@ -0,0 +1,304 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Errors and Exceptions" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Errors\n", + "\n", + "Errors (or syntax errors) are errors because the syntax is incorrect." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "invalid syntax (, line 2)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m while True\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n" + ] + } + ], + "source": [ + "# Example SyntaxError - missing semicolon in while\n", + "while True\n", + " print \"hi\"" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exceptions\n", + "Even when the syntax is correct, we can have other types of errors." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "unsupported operand type(s) for +: 'int' and 'str'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# Example TypeError - wrong use of '+' with different types\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[1;36m3\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;34m'a'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" + ] + } + ], + "source": [ + "# Example TypeError - wrong use of '+' with different types\n", + "3 + 'a'" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false, + "scrolled": true + }, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'a' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# Example NameError: variable not defined\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mNameError\u001b[0m: name 'a' is not defined" + ] + } + ], + "source": [ + "# Example NameError: variable not defined\n", + "a \n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Exceptions can be handled with the statement **try-except-else-finally**. \n", + "\n", + "* **try**: code block when an exception can occur\n", + "* **except**: code block executed if the exception ocurrs (catches the exception)\n", + "* **else**: (optional) code block executed if no exception occurs\n", + "* **finally**: (optional) code block executed always (both if there is an exception or not)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter a number: a\n", + "Oops! That was no valid number. Try again...\n", + "Please enter a number: 1\n" + ] + } + ], + "source": [ + "# Example\n", + "# Try to enter a wrong input (e.g. a) and then a number (e.g. 0)\n", + "while True:\n", + " try:\n", + " num = int(input(\"Please enter a number: \"))\n", + " break\n", + " except ValueError:\n", + " print(\"Oops! That was no valid number. Try again...\")" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter a number: a\n", + "Oops! That was no valid number. Try again...\n", + "End of input\n", + "Please enter a number: 1\n", + "End of input\n" + ] + } + ], + "source": [ + "# Example with finally\n", + "while True:\n", + " try:\n", + " num = int(input(\"Please enter a number: \"))\n", + " break\n", + " except ValueError:\n", + " print(\"Oops! That was no valid number. Try again...\")\n", + " finally:\n", + " print(\"End of input\")" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter a number: a\n", + "Oops! That was no valid number.\n", + "Number entered\n", + "Please enter a number: 1\n", + "No exception\n", + "Number entered\n" + ] + } + ], + "source": [ + "# Example with else and finally\n", + "while True:\n", + " try:\n", + " num = int(input(\"Please enter a number: \"))\n", + " except ValueError:\n", + " print(\"Oops! That was no valid number.\")\n", + " continue\n", + " else:\n", + " print(\"No exception\")\n", + " break\n", + " finally:\n", + " print(\"Number entered\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Exception can be thrown with 'raise'" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "Both arguments should be numbers or strings", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36madd\u001b[1;34m(a, b)\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0ma\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[1;32mexcept\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'", + "\nDuring handling of the above exception, another exception occurred:\n", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Both arguments should be numbers or strings\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 7\u001b[1;33m \u001b[0madd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'a'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;32m\u001b[0m in \u001b[0;36madd\u001b[1;34m(a, b)\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0ma\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;32mexcept\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Both arguments should be numbers or strings\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 6\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[0madd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'a'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mTypeError\u001b[0m: Both arguments should be numbers or strings" + ] + } + ], + "source": [ + "def add(a, b):\n", + " try:\n", + " return a + b\n", + " except:\n", + " raise TypeError(\"Both arguments should be numbers or strings\")\n", + " \n", + "add(3, 'a')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/python/1__10_Modules_Packages.ipynb b/python/1__10_Modules_Packages.ipynb new file mode 100644 index 0000000..cce1afc --- /dev/null +++ b/python/1__10_Modules_Packages.ipynb @@ -0,0 +1,187 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Course Notes for Learning Intelligent Systems" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Modules and Packages\n", + "\n", + "*Modules* contains definitions and objects that can be reused in other programmes.\n", + "\n", + "*Packages* contain subpackages of modules. They are directories and provide the namespace for modules.\n", + "\n", + "For example, let's have this package sound, a subpackage effects and the modules echo and surround:\n", + "\n", + "\n", + "babel/\n", + " messages/\n", + " \\_\\_init\\_\\_.py\n", + " plurals.py\n", + " catalog.py\n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'plurals' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# We can import the module plural with import\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mbabel\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmessages\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mplurals\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mplurals\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mget_plural\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mNameError\u001b[0m: name 'plurals' is not defined" + ] + } + ], + "source": [ + "# We can import the module plural with import, but we should use the full name\n", + "import babel.messages.plurals\n", + "plurals.get_plural()" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(2, '(n != 1)')" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import babel.messages.plurals\n", + "babel.messages.plurals.get_plural()" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(2, '(n != 1)')" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from babel.messages import plurals # with from-import, we can use the short name\n", + "plurals.get_plural()" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(2, '(n != 1)')" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from babel.messages.plurals import get_plural # now we can use directly get_plural()\n", + "get_plural()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To write a module, it is just needed to include the code in a file ended with \".py\" and the name of the file is the name of the module.\n", + "\n", + "Packages are directories that should have a file \\_\\_.init\\_\\_.py, that can be an empty file or contain initialization code." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Licence" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n", + "\n", + "© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.1" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +}