{ "metadata": { "name": "Chapter5_Types" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[Python for Developers](http://ricardoduarte.github.io/python-for-developers/#content)\n", "===================================\n", "First Edition\n", "-----------------------------------\n", "\n", "Chapter 5: Types\n", "=============================\n", "_____________________________\n", "Variables in the Python interpreter are created by assignment and destroyed by the garbage collector, when there are no more references to them.\n", "\n", "Variable names must start with a letter or underscore (`_`) and be followed by letters, digits or underscores (`_`).\u00a0 Uppercase and lowercase letters are considered different.\n", "\n", "There are several pre-defined simple types of data in Python, such as:\n", "\n", "+ Numbers (integer, real, complex, ... )\n", "+ Text\n", "\n", "Furthermore, there are types that function as collections. The main ones are:\n", "\n", "+ List\n", "+ Tuple\n", "+ Dictionary\n", "\n", "Python types can be:\n", "\n", "+ Mutable: allow the contents of the variables to be changed.\n", "+ Immutable: do not allow the contents of variables to be changed.\n", "\n", "In Python, variable names are references that can be changed at execution time.\n", "\n", "The most common types and routines are implemented in the form of *builtins*, i.e. they are always available at runtime, without the need to import any library.\n", "\n", "Numbers\n", "-------\n", "Python provides some numeric types as *builtins*:\n", "\n", "+ Integer (*int*): i = 1\n", "+ Floating Point real (*float*): f = 3.14\n", "+ Complex (*complex*): c = 3 + 4j\n", "\n", "In addition to the conventional integers, there are also long integers, whose dimensions are arbitrary and limited by the available memory. Conversions between integer and long are performed automatically. The builtin function `int()` can be used to convert other types to integer, including base changes.\n", "\n", "Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Converting real to integer\n", "print 'int(3.14) =', int(3.14)\n", "\n", "# Converting integer to real\n", "print 'float(5) =', float(5)\n", "\n", "# Calculation between integer and real results in real\n", "print '5.0 / 2 + 3 = ', 5.0 / 2 + 3\n", "\n", "# Integers in other base\n", "print \"int('20', 8) =\", int('20', 8) # base 8\n", "print \"int('20', 16) =\", int('20', 16) # base 16\n", "\n", "# Operations with complex numbers\n", "c = 3 + 4j\n", "print 'c =', c\n", "print 'Real Part:', c.real\n", "print 'Imaginary Part:', c.imag\n", "print 'Conjugate:', c.conjugate()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "int(3.14) = 3\n", "float(5) = 5.0\n", "5.0 / 2 + 3 = 5.5\n", "int('20', 8) = 16\n", "int('20', 16) = 32\n", "c = (3+4j)\n", "Real Part: 3.0\n", "Imaginary Part: 4.0\n", "Conjugate: (3-4j)\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The real numbers can also be represented in scientific notation, for example: 1.2e22.\n", "\n", "Python has a number of defined operators for handling numbers through arithmetic calculations, logic operations (that test whether a condition is true or false) or bitwise processing (where the numbers are processed in binary form).\n", "\n", "Arithmetic Operations:\n", "\n", "+ Sum (+)\n", "+ Difference (-)\n", "+ Multiplication (*)\n", "+ Division (/): between two integers the result is equal to the integer division. In other cases, the result is real.\n", "+ Integer Division (//): the result is truncated to the next lower integer, even when applied to real numbers, but in this case the result type is real too.\n", "+ Module (%): returns the remainder of the division.\n", "+ Power (**): can be used to calculate the root, through fractional exponents (eg `100 ** 0.5`).\n", "+ Positive (+)\n", "+ Negative (-)\n", "\n", "Logical Operations:\n", "\n", "+ Less than (<)\n", "+ Greater than (>)\n", "+ Less than or equal to (<=)\n", "+ Greater than or equal to (>=)\n", "+ Equal to (==)\n", "+ Not equal to (!=)\n", "\n", "Bitwise Operations:\n", "\n", "+ Left Shift (<<)\n", "+ Right Shift (>>)\n", "+ And (&)\n", "+ Or (|)\n", "+ Exclusive Or (^)\n", "+ Inversion (~)\n", "\n", "During the operations, numbers are converted appropriately (eg. `(1.5+4j) + 3` gives `4.5+4j`).\n", "\n", "Besides operators, there are also some *builtin* features to handle numeric types: `abs()`, which returns the absolute value of the number, `oct()`, which converts to octal, `hex()`, which converts for hexadecimal, `pow()`, which raises a number by another and `round()`, which returns a real number with the specified rounding.\n", "\n", "Text\n", "-----\n", "*Strings* are Python *builtins* for handling text. As they are immutable, you can not add, remove or change any character in a *string*. To perform these operations, Python needs to create a new *string*.\n", "\n", "Types:\n", "\n", "+ Standard String: `s = 'Led Zeppelin'`\n", "+ Unicode String: `u = u'Bj\u00f6rk'`\n", "\n", "The standard *string* can be converted to *unicode* by using the function `unicode()`.\n", "\n", "String initializations can be made:\n", "\n", "+ With single or double quotes.\n", "+ On several consecutive lines, provided that it's between three single or double quotes.\n", "+ Without expansion characters (example: `s = r '\\ n'`, where `s` will contain the characters `\\` and `n`).\n", "\n", "String Operations:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "s = 'Camel'\n", "\n", "# Concatenation\n", "print 'The ' + s + ' ran away!'\n", "\n", "# Interpolation\n", "print 'Size of %s => %d' % (s, len(s))\n", "\n", "# String processed as a sequence\n", "for ch in s: print ch\n", "\n", "# Strings are objects\n", "if s.startswith('C'): print s.upper()\n", "\n", "# what will happen? \n", "print 3 * s\n", "# 3 * s is consistent with s + s + s" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The Camel run away!\n", "Size of Camel => 5\n", "C\n", "a\n", "m\n", "e\n", "l\n", "CAMEL\n", "CamelCamelCamel\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The operator `%` is used for string interpolation. The interpolation is more efficient in use of memory than the conventional concatenation.\n", "\n", "Symbols used in the interpolation:\n", "\n", "+ %s: *string*.\n", "+ %d: integer.\n", "+ %o: octal.\n", "+ %x: hexacimal.\n", "+ %f: real.\n", "+ %e: real exponential.\n", "+ %%: percent sign.\n", "\n", "Symbols can be used to display numbers in various formats.\n", "\n", "Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Zeros left\n", "print 'Now is %02d:%02d.' % (16, 30)\n", "\n", "# Real (The number after the decimal point specifies how many decimal digits )\n", "print 'Percent: %.1f%%, Exponencial:%.2e' % (5.333, 0.00314)\n", "\n", "# Octal and hexadecimal\n", "print 'Decimal: %d, Octal: %o, Hexadecimal: %x' % (10, 10, 10)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Now is 16:30.\n", "Percent: 5.3%, Exponencial:3.14e-03\n", "Decimal: 10, Octal: 12, Hexadecimal: a\n" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since version 2.6, in addition to interpolation operator `%`, the string method and function `format()` is available.\n", "Examples:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "musicians = [('Page', 'guitarist', 'Led Zeppelin'),\n", "('Fripp', 'guitarist', 'King Crimson')]\n", "\n", "# Parameters are identified by order\n", "msg = '{0} is {1} of {2}'\n", "\n", "for name, function, band in musicians:\n", " print(msg.format(name, function, band))\n", "\n", "# Parameters are identified by name\n", "msg = '{greeting}, it is {hour:02d}:{minute:02d}'\n", "\n", "print msg.format(greeting='Good Morning', hour=7, minute=30)\n", "\n", "# Builtin function format()\n", "print 'Pi =', format(3.14159, '.3e')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Page is guitarist of Led Zeppelin\n", "Fripp is guitarist of King Crimson\n", "Good Morning, it is 07:30\n", "Pi = 3.142e+00\n" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function `format()` can be used only to format one piece of data each time.\n", "\n", "*Slices* of *strings* can be obtained by adding indexes between brackets after a *string*.\n", "\n", "![Slicing strings](files/bpyfd_diags4.png)\n", "\n", "Python indexes:\n", "\n", "+ Start with zero.\n", "+ Count from the end if they are negative.\n", "+ Can be defined as sections, in the form `[start: end + 1: step]`. If not set the start, it will be considered as zero. If not set end + 1, it will be considered the size of the object. The step (between characters), if not set, is 1.\n", "\n", "It is possible to invert *strings* by using a negative step:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print 'Python'[::-1]\n", "# shows: nohtyP" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "nohtyP\n" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Various functions for dealing with text are implemented in the module *string*." ] }, { "cell_type": "code", "collapsed": false, "input": [ "import string\n", "\n", "# the alphabet\n", "a = string.ascii_letters\n", "\n", "# Shifting left the alphabet\n", "b = a[1:] + a[0]\n", "\n", "# The function maketrans() creates a translation table\n", "# from the characters of both strings it received as parameters.\n", "# The characters not present in the table will be \n", "# copied to the output.\n", "tab = string.maketrans(a, b)\n", "\n", "# The message...\n", "msg = '''This text will be translated..\n", "It will become very strange.\n", "'''\n", "# The function translate() uses the translation table\n", "# created by maketrans() to translate the string\n", "print string.translate(msg, tab)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Uijt ufyu xjmm cf usbotmbufe..\n", "Ju xjmm cfdpnf wfsz tusbohf.\n", "\n" ] } ], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The module also implements a type called *Template*, which is a model *string* that can be filled through a dictionary. Identifiers are initialized by a dollar sign ($) and may be surrounded by curly braces, to avoid confusion.\n", "\n", "Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import string\n", "\n", "# Creates a template string\n", "st = string.Template('$warning occurred in $when')\n", "\n", "# Fills the model with a dictionary\n", "s = st.substitute({'warning': 'Lack of electricity',\n", " 'when': 'April 3, 2002'})\n", "\n", "# Shows:\n", "# Lack of electricity occurred in April 3, 2002\n", "print s" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Lack of electricity occurred in April 3, 2002\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is possible to use *mutable* strings in Python through the UserString *module*, which defines the *MutableString* type" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import UserString\n", "\n", "s = UserString.MutableString('Python')\n", "s[0] = 'p'\n", "\n", "print s # shows \"python\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "python\n" ] } ], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Mutable *Strings* are less efficient than immutable *strings*, as they are more complex (in terms of the structure), which is reflected in increased consumption of resources (CPU and memory).\n", "The *unicode* strings can be converted to conventional strings through the `decode()` method and the reverse path can be done by the method `encode()`.\n", "Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Unicode String \n", "u = u'H\u00fcsker D\u00fc'\n", "# Convert to str\n", "s = u.encode('latin1')\n", "print s, '=>', type(s)\n", "\n", "# String str\n", "s = 'H\u00fcsker D\u00fc'\n", "u = s.decode('latin1')\n", "\n", "print repr(u), '=>', type(u)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "H\ufffdsker D\ufffd => \n", "u'H\\xc3\\xbcsker D\\xc3\\xbc' => \n" ] } ], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "To use both methods, it is necessary to pass as an argument the compliant coding. The most used are \"latin1\" \"utf8\".\n", "\n", "Lists\n", "------\n", "Lists are collections of heterogeneous objects, which can be of any type, including other lists.\n", "\n", "Lists in the Python are mutable and can be changed at any time. Lists can be sliced \u200b\u200bin the same way as *strings*, but as the lists are mutable, it is possible to make assignments to the list items.\n", "\n", "Syntax:\n", "\n", " list = [a, b, ..., z]\n", "\n", "Common operations with lists:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# a new list: 70s Brit Progs\n", "progs = ['Yes', 'Genesis', 'Pink Floyd', 'ELP']\n", "\n", "# processing the entire list\n", "for prog in progs:\n", " print prog\n", "\n", "# Changing the last element\n", "progs[-1] = 'King Crimson'\n", "\n", "# Including\n", "progs.append('Camel')\n", "\n", "# Removing\n", "progs.remove('Pink Floyd')\n", "\n", "# Ordering \n", "progs.sort()\n", "\n", "# Inverting\n", "progs.reverse()\n", "\n", "# prints with number order\n", "for i, prog in enumerate(progs):\n", " print i + 1, '=>', prog\n", "\n", "# prints from de second item\n", "print progs[1:]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Yes\n", "Genesis\n", "Pink Floyd\n", "ELP\n", "1 => Yes\n", "2 => King Crimson\n", "3 => Genesis\n", "4 => Camel\n", "['King Crimson', 'Genesis', 'Camel']\n" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function `enumerate()` returns a tuple of two elements in each iteration: a sequence number and an item from the corresponding sequence.\n", "\n", "The list has a `pop()` method that helps the implementation of queues and stacks:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "my_list = ['A', 'B', 'C']\n", "print 'list:', my_list\n", "\n", "# The empty list is evaluated as false\n", "while my_list:\n", " # In queues, the first item is the first to go out\n", " # pop(0) removes and returns the first item \n", " print 'Left', my_list.pop(0), ', remain', len(my_list)\n", "\n", "# More items on the list\n", "my_list += ['D', 'E', 'F']\n", "print 'list:', my_list\n", "\n", "while my_list:\n", " # On stacks, the first item is the last to go out\n", " # pop() removes and retorns the last item\n", " print 'Left', my_list.pop(), ', remain', len(my_list)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "list: ['A', 'B', 'C']\n", "Left A , remain 2\n", "Left B , remain 1\n", "Left C , remain 0\n", "list: ['D', 'E', 'F']\n", "Left F , remain 2\n", "Left E , remain 1\n", "Left D , remain 0\n" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The sort (*sort*) and reversal (*reverse*) operations are performed in the list and do not create new lists.\n", "\n", "Tuples\n", "------\n", "Similar to lists, but immutable: it's not possible to append, delete or make assignments to the items.\n", "\n", "Syntax:\n", "\n", " my_tuple = (a, b, ..., z)\n", "\n", "The parentheses are optional.\n", "\n", "Feature: a tuple with only one element is represented as:\n", "\n", "t1 = (1,)\n", "\n", "The tuple elements can be referenced the same way as the elements of a list:\n", "\n", " first_element = tuple[0]\n", "\n", "Lists can be converted into tuples:\n", "\n", " my_tuple = tuple(my_list)\n", "\n", "And tuples can be converted into lists:\n", "\n", " my_list = list(my_tuple)\n", "\n", "While tuple can contain mutable elements, these elements can not undergo assignment, as this would change the reference to the object.\n", "\n", "Example (using the interactive mode):\n", "\n", " >>> t = ([1, 2], 4)\n", " >>> t[0].append(3)\n", " >>> t\n", " ([1, 2, 3], 4)\n", " >>> t[0] = [1, 2, 3]\n", " Traceback (most recent call last):\n", " File \"\", line 1, in ?\n", " TypeError: object does not support item assignment\n", " >>>\n", "\n", "Tuples are more efficient than conventional lists, as they consume less computing resources (memory)\u00a0because they are simpler structures the same way *immutable* strings are in relation to *mutable* strings.\n", "\n", "Other types of sequences\n", "--------------------------\n", "Also in the *builtins*, Python provides:\n", "\n", "+ *set*: mutable sequence univocal (without repetitions) unordered.\n", "+ *frozenset*: immutable sequence univocal unordered.\n", "\n", "Both types implement set operations, such as: union, intersection e difference.\n", "\n", "Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Data sets\n", "s1 = set(range(3))\n", "s2 = set(range(10, 7, -1))\n", "s3 = set(range(2, 10, 2))\n", "\n", "# Shows the data\n", "print 's1:', s1, '\\ns2:', s2, '\\ns3:', s3\n", "\n", "# Union\n", "s1s2 = s1.union(s2)\n", "print 'Union of s1 and s2:', s1s2\n", "\n", "# Difference\n", "print 'Difference with s3:', s1s2.difference(s3)\n", "\n", "# Intersectiono\n", "print 'Intersection with s3:', s1s2.intersection(s3)\n", "\n", "# Tests if a set includes the other\n", "if s1.issuperset([1, 2]):\n", " print 's1 includes 1 and 2'\n", "\n", "# Tests if there is no common elements\n", "if s1.isdisjoint(s2):\n", " print 's1 and s2 have no common elements'" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "s1: set([0, 1, 2]) \n", "s2: set([8, 9, 10]) \n", "s3: set([8, 2, 4, 6])\n", "Union of s1 and s2: set([0, 1, 2, 8, 9, 10])\n", "Difference with s3: set([0, 1, 10, 9])\n", "Intersection with s3: set([8, 2])\n", "s1 includes 1 and 2\n", "s1 and s2 have no common elements\n" ] } ], "prompt_number": 13 }, { "cell_type": "markdown", "metadata": {}, "source": [ "When one list is converted to a *set*, the repetitions are discarded.\n", "\n", "In version 2.6, a *builtin* type for mutable characters list, called *bytearray* is also available.\n", "\n", "Dictionaries\n", "-----------\n", "A dictionary is a list of associations composed by a unique key and corresponding structures. Dictionaries are mutable, like lists.\n", "\n", "The key must be an immutable type, usually strings, but can also be tuples or numeric types. On the other hand the items of dictionaries can be either mutable or immutable. The Python dictionary provides no guarantee that the keys are ordered.\n", "\n", "Syntax:\n", "\n", " dictionary = {'a': a, 'b': b, ..., 'z': z}\n", "\n", "Structure:\n", "\n", "![Structure of a dictionary](files/bpyfd_diags5.png)\n", "\n", "Example of a dictionary:\n", "\n", " dic = {'name': 'Shirley Manson', 'band': 'Garbage'}\n", "\n", "Acessing elements:\n", "\n", " print dic['name']\n", "\n", "Adding elements:\n", "\n", " dic['album'] = 'Version 2.0'\n", "\n", "Removing one elemento from a dictionary:\n", "\n", " del dic['album']\n", "\n", "Getting the items, keys and values:\n", "\n", " items = dic.items()\n", " keys = dic.keys()\n", " values = dic.values()\n", "\n", "Examples with dictionaries:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Progs and their albums\n", "progs = {'Yes': ['Close To The Edge', 'Fragile'],\n", " 'Genesis': ['Foxtrot', 'The Nursery Crime'],\n", " 'ELP': ['Brain Salad Surgery']}\n", "\n", "# More progs\n", "progs['King Crimson'] = ['Red', 'Discipline']\n", "\n", "# items() returns a list of \n", "# tuples with key and value \n", "for prog, albums in progs.items():\n", " print prog, '=>', albums\n", "\n", "# If there is 'ELP', removes\n", "if progs.has_key('ELP'):\n", " del progs['ELP']" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Yes => ['Close To The Edge', 'Fragile']\n", "ELP => ['Brain Salad Surgery']\n", "Genesis => ['Foxtrot', 'The Nursery Crime']\n", "King Crimson => ['Red', 'Discipline']\n" ] } ], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sparse matrix example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Sparse Matrix implemented\n", "# with dictionary\n", "\n", "# Sparse Matrix is a structure\n", "# that only stores values that are\n", "# present in the matrix\n", "\n", "dim = 6, 12\n", "mat = {}\n", "\n", "# Tuples are immutable\n", "# Each tuple represents\n", "# a position in the matrix\n", "mat[3, 7] = 3\n", "mat[4, 6] = 5\n", "mat[6, 3] = 7\n", "mat[5, 4] = 6\n", "mat[2, 9] = 4\n", "mat[1, 0] = 9\n", "\n", "for lin in range(dim[0]):\n", " for col in range(dim[1]):\n", " # Method get(key, value)\n", " # returns the key value\n", " # in dictionary or \n", " # if the key doesn't exists\n", " # returns the second argument\n", " print mat.get((lin, col), 0),\n", " print" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "0 0 0 0 0 0 0 0 0 0 0 0\n", "9 0 0 0 0 0 0 0 0 0 0 0\n", "0 0 0 0 0 0 0 0 0 4 0 0\n", "0 0 0 0 0 0 0 3 0 0 0 0\n", "0 0 0 0 0 0 5 0 0 0 0 0\n", "0 0 0 0 6 0 0 0 0 0 0 0\n" ] } ], "prompt_number": 17 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Generating the sparse matrix:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Matrix in form of string\n", "matrix = '''0 0 0 0 0 0 0 0 0 0 0 0\n", "9 0 0 0 0 0 0 0 0 0 0 0\n", "0 0 0 0 0 0 0 0 0 4 0 0\n", "0 0 0 0 0 0 0 3 0 0 0 0\n", "0 0 0 0 0 0 5 0 0 0 0 0\n", "0 0 0 0 6 0 0 0 0 0 0 0'''\n", "\n", "mat = {}\n", "\n", "# split the matrix in lines\n", "for row, line in enumerate(matrix.splitlines()):\n", "\n", " # Splits the line int cols\n", " for col, column in enumerate(line.split()):\n", "\n", " column = int(column)\n", " # Places the column in the result,\n", " # if it is differente from zero\n", " if column:\n", " mat[row, col] = column\n", "\n", "print mat\n", "# The counting starts with zero\n", "print 'Complete matrix size:', (row + 1) * (col + 1)\n", "print 'Sparse matrix size:', len(mat)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ " {(5, 4): 6, (3, 7): 3, (1, 0): 9, (4, 6): 5, (2, 9): 4}\n", "Complete matrix size: 72\n", "Sparse matrix size: 5\n" ] } ], "prompt_number": 18 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The sparse matrix is a good solution for processing structures in which most of the items remain empty, like spreadsheets for example.\n", "\n", "True, False and Null\n", "------------------------\n", "In Python, the boolean type (*bool*) is a specialization of the integer type (*int*). The *True* value is equal to 1, while the *False* value is equal to zero.\n", "\n", "The following values \u200b\u200bare considered false:\n", "\n", "+ `False`.\n", "+ `None` (null).\n", "+ `0` (zero).\n", "+ `''` (empty string).\n", "+ `[]` (empty list).\n", "+ `()` (empty tuple).\n", "+ `{}` (emtpy dicionary).\n", "+ Other structures with size equal zero.\n", "\n", "All other objects out of that list are considered true.\n", "\n", "The object *None*, which is of type *NoneType*, in Python represents the null and is evaluated as false by the interpreter.\n", "\n", "Boolean Operators\n", "--------------------\n", "With logical operators it is possible to build more complex conditions to control conditional jumps and loops.\n", "\n", "Boolean operators in Python are: *and*, *or* , *not* , *is* , *in*.\n", "\n", "+ `and`: returns a true value if and only if it receives two expressions that are true.\n", "+ `or` : returns a false value if and only if it receives two expressions that are false.\n", "+ `not` : returns false if it receives a true expression and vice versa.\n", "+ `is`: returns true if it receives two references to the same object false otherwise.\n", "+ `in` : returns true if you receive an item and a list and the item occur one or more times in the list false otherwise.\n", "\n", "The calculation of the resulting operation *and* is as follows: if the first expression is true, the result will be the second expression, otherwise it will be the first. \n", "\n", "As for the operator *or* if the first expression is false, the result will be the second expression, otherwise it will be the first. For other operators, the return will be of type bool (True or False).\n", "\n", "Examples:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print 0 and 3 # Shows 0\n", "print 2 and 3 # Shows 3\n", "\n", "print 0 or 3 # Shows 3\n", "print 2 or 3 # Shows 2\n", "\n", "print not 0 # Shows True\n", "print not 2 # Shows False\n", "print 2 in (2, 3) # Shows True\n", "print 2 is 3 # Shows False" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "0\n", "3\n", "3\n", "2\n", "True\n", "False\n", "True\n", "False\n" ] } ], "prompt_number": 20 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Besides boolean operators, there are the functions `all()`, which returns true when all of the items in the sequence passed as parameters are true, and `any()`, which returns true if any item is true." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", "" ], "output_type": "pyout", "prompt_number": 1, "text": [ "" ] } ], "prompt_number": 1 } ], "metadata": {} } ] }