day1/Session-4.tex~
changeset 46 63704b5650f1
equal deleted inserted replaced
45:3b8be02d94d4 46:63704b5650f1
       
     1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
     2 % Tutorial slides on Python.
       
     3 %
       
     4 % Author: Prabhu Ramachandran <prabhu at aero.iitb.ac.in>
       
     5 % Copyright (c) 2005-2008, Prabhu Ramachandran
       
     6 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
     7 
       
     8 \documentclass[14pt,compress]{beamer}
       
     9 %\documentclass[draft]{beamer}
       
    10 %\documentclass[compress,handout]{beamer}
       
    11 %\usepackage{pgfpages} 
       
    12 %\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm]
       
    13 
       
    14 % Modified from: generic-ornate-15min-45min.de.tex
       
    15 \mode<presentation>
       
    16 {
       
    17   \usetheme{Warsaw}
       
    18   \useoutertheme{split}
       
    19   \setbeamercovered{transparent}
       
    20 }
       
    21 
       
    22 \usepackage[english]{babel}
       
    23 \usepackage[latin1]{inputenc}
       
    24 %\usepackage{times}
       
    25 \usepackage[T1]{fontenc}
       
    26 
       
    27 % Taken from Fernando's slides.
       
    28 \usepackage{ae,aecompl}
       
    29 \usepackage{mathpazo,courier,euler}
       
    30 \usepackage[scaled=.95]{helvet}
       
    31 
       
    32 \definecolor{darkgreen}{rgb}{0,0.5,0}
       
    33 
       
    34 \usepackage{listings}
       
    35 \lstset{language=Python,
       
    36     basicstyle=\ttfamily\bfseries,
       
    37     commentstyle=\color{red}\itshape,
       
    38   stringstyle=\color{darkgreen},
       
    39   showstringspaces=false,
       
    40   keywordstyle=\color{blue}\bfseries}
       
    41 
       
    42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
    43 % Macros
       
    44 \setbeamercolor{emphbar}{bg=blue!20, fg=black}
       
    45 \newcommand{\emphbar}[1]
       
    46 {\begin{beamercolorbox}[rounded=true]{emphbar} 
       
    47       {#1}
       
    48  \end{beamercolorbox}
       
    49 }
       
    50 \newcounter{time}
       
    51 \setcounter{time}{0}
       
    52 \newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}}
       
    53 
       
    54 \newcommand{\typ}[1]{\texttt{#1}}
       
    55 
       
    56 \newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}}  }
       
    57 
       
    58 %%% This is from Fernando's setup.
       
    59 % \usepackage{color}
       
    60 % \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
       
    61 % % Use and configure listings package for nicely formatted code
       
    62 % \usepackage{listings}
       
    63 % \lstset{
       
    64 %    language=Python,
       
    65 %    basicstyle=\small\ttfamily,
       
    66 %    commentstyle=\ttfamily\color{blue},
       
    67 %    stringstyle=\ttfamily\color{orange},
       
    68 %    showstringspaces=false,
       
    69 %    breaklines=true,
       
    70 %    postbreak = \space\dots
       
    71 % }
       
    72 
       
    73 
       
    74 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
    75 % Title page
       
    76 \title[Basic Python]{Python:\\Advanced Python data structures, Functions and Debugging}
       
    77 
       
    78 \author[FOSSEE Team] {Asokan Pichai\\Prabhu Ramachandran}
       
    79 
       
    80 \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay}
       
    81 \date[] {10, October 2009}
       
    82 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
    83 
       
    84 %\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo}
       
    85 %\logo{\pgfuseimage{iitmlogo}}
       
    86 
       
    87 
       
    88 %% Delete this, if you do not want the table of contents to pop up at
       
    89 %% the beginning of each subsection:
       
    90 \AtBeginSubsection[]
       
    91 {
       
    92   \begin{frame}<beamer>
       
    93     \frametitle{Outline}
       
    94     \tableofcontents[currentsection,currentsubsection]
       
    95   \end{frame}
       
    96 }
       
    97 
       
    98 
       
    99 % If you wish to uncover everything in a step-wise fashion, uncomment
       
   100 % the following command: 
       
   101 %\beamerdefaultoverlayspecification{<+->}
       
   102 
       
   103 %\includeonlyframes{current,current1,current2,current3,current4,current5,current6}
       
   104 
       
   105 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
   106 % DOCUMENT STARTS
       
   107 \begin{document}
       
   108 
       
   109 \begin{frame}
       
   110   \titlepage
       
   111 \end{frame}
       
   112 
       
   113 \section{Python}
       
   114 
       
   115 \subsection{Dictionary}
       
   116 \begin{frame}{Dictionary}
       
   117   \begin{itemize}
       
   118     \item aka associative arrays, key-value pairs, hashmaps, hashtables \ldots    
       
   119     \item \typ{ d = \{ ``Hitchhiker's guide'' : 42, ``Terminator'' : ``I'll be back''\}}
       
   120     \item lists and tuples index: 0 \ldots n
       
   121     \item dictionaries index using strings
       
   122     \item aka key-value pairs
       
   123     \item what can be keys?
       
   124   \end{itemize}
       
   125 \end{frame}
       
   126 
       
   127 \begin{frame}{Dictionary \ldots }
       
   128   \begin{itemize}
       
   129     \item \alert{Unordered}
       
   130       \begin{block}{Standard usage}
       
   131         for key in dict:\\
       
   132             <use> dict[key] \# => value
       
   133       \end{block}
       
   134     \item \typ{d.keys()} returns a list
       
   135     \item can we have duplicate keys?
       
   136   \end{itemize}
       
   137   \inctime{5}
       
   138 \end{frame}
       
   139 
       
   140 \begin{frame} {Problem Set 2.1}
       
   141   \begin{description}
       
   142 \item[2.1.1] You are given date strings of the form ``29, Jul 2009'', or ``4 January 2008''. In other words a number a string and another number, with a comma sometimes separating the items.Write a function that takes such a string and returns a tuple (yyyy, mm, dd) where all three elements are ints.
       
   143     \item[2.1.2] Count word frequencies in a file.
       
   144     \item[2.1.3] Find the most used Python keywords in your Python code (import keyword).
       
   145 \end{description}
       
   146 
       
   147 \inctime{10}
       
   148 \end{frame}
       
   149 
       
   150 \subsection{Set}
       
   151 \begin{frame}[fragile]
       
   152   \frametitle{Set}
       
   153     \begin{itemize}
       
   154       \item Simplest container, mutable
       
   155       \item No ordering, no duplicates
       
   156       \item usual suspects: union, intersection, subset \ldots
       
   157       \item >, >=, <, <=, in, \ldots
       
   158     \end{itemize}
       
   159     \begin{lstlisting}
       
   160 >>> f10 = set([1,2,3,5,8])
       
   161 >>> p10 = set([2,3,5,7])
       
   162 >>> f10|p10
       
   163 set([1, 2, 3, 5, 7, 8])
       
   164 >>> f10&p10
       
   165 set([2, 3, 5])
       
   166 >>> f10-p10
       
   167 set([8, 1])
       
   168 \end{lstlisting}
       
   169 \end{frame}
       
   170 
       
   171 \begin{frame}[fragile]
       
   172   \frametitle{Set}
       
   173     \begin{lstlisting}
       
   174 >>> p10-f10, f10^p10
       
   175 set([7]), set([1, 7, 8])
       
   176 >>> set([2,3]) < p10
       
   177 True
       
   178 >>> set([2,3]) <= p10
       
   179 True
       
   180 >>> 2 in p10
       
   181 True
       
   182 >>> 4 in p10
       
   183 False
       
   184 >>> len(f10)
       
   185 5
       
   186 \end{lstlisting}
       
   187 \inctime{5}
       
   188 \end{frame}
       
   189 
       
   190 
       
   191 \begin{frame}
       
   192   \frametitle{Problem set 2.2}
       
   193   \begin{description}
       
   194     \item[2.2.1] Given a dictionary of the names of students and their marks, identify how many duplicate marks are there? and what are these?
       
   195     \item[2.2.2] Given a string of the form ``4-7, 9, 12, 15'' find the numbers missing in this list for a given range.
       
   196 \end{description}
       
   197 \inctime{10}
       
   198 \end{frame}
       
   199 
       
   200 \subsection{Functions Reloaded!}
       
   201 \begin{frame}[fragile]
       
   202     \frametitle{Advanced functions}
       
   203     \begin{itemize}
       
   204         \item default args
       
   205         \item var args
       
   206         \item keyword args
       
   207         \item scope
       
   208         \item \typ{global}
       
   209       \end{itemize}
       
   210 \end{frame}
       
   211 
       
   212 \begin{frame}[fragile]
       
   213   \frametitle{Functions: default arguments}
       
   214   \small
       
   215   \begin{lstlisting}
       
   216 def ask_ok(prompt, retries=4,
       
   217            complaint='Yes or no!'):
       
   218     while True:
       
   219         ok = raw_input(prompt)
       
   220         if ok in ('y', 'ye', 'yes'): 
       
   221             return True
       
   222         if ok in ('n', 'no', 'nop',
       
   223                   'nope'): 
       
   224             return False
       
   225         retries = retries - 1
       
   226         if retries < 0: 
       
   227             raise IOError, 'bad user'
       
   228         print complaint
       
   229   \end{lstlisting}
       
   230 \end{frame}
       
   231 
       
   232 \begin{frame}[fragile]
       
   233   \frametitle{Functions: keyword arguments}
       
   234   \small
       
   235   \begin{lstlisting}
       
   236 def parrot(voltage, state='a stiff', 
       
   237            action='voom', type='Royal Blue'):
       
   238     print "-- This parrot wouldn't", action,
       
   239     print "if you supply", voltage, "Volts."
       
   240     print "-- Lovely plumage, the", type
       
   241     print "-- It's", state, "!"
       
   242 
       
   243 parrot(1000)
       
   244 parrot(action = 'VOOOOOM', voltage = 1000000)
       
   245 parrot('a thousand',
       
   246        state = 'pushing up the daisies')
       
   247 parrot('a million', 'bereft of life', 'jump')
       
   248 \end{lstlisting}
       
   249 \end{frame}
       
   250 
       
   251 \begin{frame}[fragile]
       
   252   \frametitle{Functions: arbitrary argument lists}
       
   253   \begin{itemize}
       
   254   \item Arbitrary number of arguments using \verb+*args+ or
       
   255     \verb+*whatever+
       
   256   \item Keyword arguments using \verb+**kw+
       
   257   \item Given a tuple/dict how do you call a function?
       
   258     \begin{itemize}
       
   259     \item Using argument unpacking
       
   260     \item For positional arguments: \verb+foo(*[5, 10])+
       
   261     \item For keyword args: \verb+foo(**{'a':5, 'b':10})+
       
   262     \end{itemize}
       
   263   \end{itemize}
       
   264 \end{frame}
       
   265 
       
   266   \begin{frame}[fragile]
       
   267 \begin{lstlisting}
       
   268 def foo(a=10, b=100):
       
   269     print a, b
       
   270 def func(*args, **keyword):
       
   271     print args, keyword
       
   272 # Unpacking:
       
   273 args = [5, 10]
       
   274 foo(*args)
       
   275 kw = {'a':5, 'b':10}
       
   276 foo(**kw)
       
   277 \end{lstlisting}
       
   278     \inctime{15} 
       
   279 \end{frame}
       
   280 
       
   281 \subsection{Functional programming}
       
   282 \begin{frame}[fragile]
       
   283     \frametitle{Functional programming}
       
   284 What is the basic idea?\\
       
   285 Why is it interesting?\\
       
   286 \typ{map, reduce, filter}\\
       
   287 list comprehension\\
       
   288 generators
       
   289     \inctime{15} 
       
   290 \end{frame}
       
   291 
       
   292 \subsection{Debugging}
       
   293 \begin{frame}[fragile]
       
   294  \frametitle{Errors}
       
   295  \begin{lstlisting}
       
   296 >>> while True print 'Hello world'
       
   297   File "<stdin>", line 1, in ?
       
   298     while True print 'Hello world'
       
   299                    ^
       
   300 SyntaxError: invalid syntax
       
   301 \end{lstlisting}
       
   302 \end{frame}
       
   303 
       
   304 \begin{frame}[fragile]
       
   305  \frametitle{Exceptions}
       
   306  \begin{lstlisting}
       
   307 >>> print spam
       
   308 Traceback (most recent call last):
       
   309   File "<stdin>", line 1, in <module>
       
   310 NameError: name 'spam' is not defined
       
   311 
       
   312 >>> 1 / 0
       
   313 Traceback (most recent call last):
       
   314   File "<stdin>", line 1, in <module>
       
   315 ZeroDivisionError: integer division 
       
   316 or modulo by zero
       
   317 \end{lstlisting}
       
   318 \end{frame}
       
   319 
       
   320 \begin{frame}[fragile]
       
   321     \frametitle{Debugging effectively}
       
   322 
       
   323     \begin{itemize}
       
   324         \item  \kwrd{print} based strategy
       
   325         \item Process: Hypothesis, test, refine, rinse-repeat
       
   326         \item Using \typ{\%debug} and \typ{\%pdb} in IPython
       
   327     \end{itemize}
       
   328     \inctime{15} 
       
   329 \end{frame}
       
   330 
       
   331 \begin{frame}[fragile]
       
   332 \frametitle{Debugging: example}
       
   333 \small
       
   334 \begin{lstlisting}
       
   335 >>> import pdb
       
   336 >>> import mymodule
       
   337 >>> pdb.run('mymodule.test()')
       
   338 > <string>(1)<module>()
       
   339 (Pdb) continue
       
   340 Traceback (most recent call last):
       
   341   File "<stdin>", line 1, in <module>
       
   342   File "/usr/lib/python2.6/pdb.py", line 1207, in run
       
   343     Pdb().run(statement, globals, locals)
       
   344   File "/usr/lib/python2.6/bdb.py", line 368, in run
       
   345     exec cmd in globals, locals
       
   346   File "<string>", line 1, in <module>
       
   347   File "mymodule.py", line 2, in test
       
   348     print spam
       
   349 NameError: global name 'spam' is not defined
       
   350 \end{lstlisting}
       
   351 \end{frame}
       
   352 
       
   353 \begin{frame}[fragile]
       
   354 \frametitle{Debugging in IPython}
       
   355 \small
       
   356 \begin{lstlisting}
       
   357 In [1]: %pdb
       
   358 Automatic pdb calling has been turned ON
       
   359 In [2]: import mymodule
       
   360 In [3]: mymodule.test()
       
   361 ----------------------------------------------
       
   362 NameError    Traceback (most recent call last)
       
   363 /media/python/iitb/workshops/day1/<ipython console> in <module>()
       
   364 /media/python/iitb/workshops/day1/mymodule.pyc in test()
       
   365       1 def test():
       
   366 ----> 2     print spam
       
   367 NameError: global name 'spam' is not defined
       
   368 > /media/python/iitb/workshops/day1/mymodule.py(2)test()
       
   369       0     print spam
       
   370 ipdb>
       
   371 \end{lstlisting}
       
   372 \end{frame}
       
   373 
       
   374 \begin{frame}[fragile]
       
   375 \frametitle{Debugging: Exercise}
       
   376 \end{frame}
       
   377 
       
   378 \end{document}