day1/Session-4.tex
changeset 114 346f3a7e5da5
parent 113 e7febbccd376
parent 112 24992ab48f2b
child 115 66709e58f765
equal deleted inserted replaced
113:e7febbccd376 114:346f3a7e5da5
     1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
     2 % Tutorial slides on Python.
       
     3 %
       
     4 % Author: Prabhu Ramachandran <prabhu at aero.iitb.ac.in>
       
     5 % Copyright (c) 2005-2009, 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 \usepackage{pgf}
       
    43 
       
    44 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
    45 % Macros
       
    46 \setbeamercolor{emphbar}{bg=blue!20, fg=black}
       
    47 \newcommand{\emphbar}[1]
       
    48 {\begin{beamercolorbox}[rounded=true]{emphbar} 
       
    49       {#1}
       
    50  \end{beamercolorbox}
       
    51 }
       
    52 \newcounter{time}
       
    53 \setcounter{time}{0}
       
    54 \newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}}
       
    55 
       
    56 \newcommand{\typ}[1]{\texttt{#1}}
       
    57 
       
    58 \newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}}  }
       
    59 
       
    60 %%% This is from Fernando's setup.
       
    61 % \usepackage{color}
       
    62 % \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
       
    63 % % Use and configure listings package for nicely formatted code
       
    64 % \usepackage{listings}
       
    65 % \lstset{
       
    66 %    language=Python,
       
    67 %    basicstyle=\small\ttfamily,
       
    68 %    commentstyle=\ttfamily\color{blue},
       
    69 %    stringstyle=\ttfamily\color{orange},
       
    70 %    showstringspaces=false,
       
    71 %    breaklines=true,
       
    72 %    postbreak = \space\dots
       
    73 % }
       
    74 
       
    75 
       
    76 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
    77 % Title page
       
    78 \title[Basic Python]{Python:\\Advanced Python data structures, Functions and Debugging}
       
    79 
       
    80 \author[FOSSEE Team] {Asokan Pichai\\Prabhu Ramachandran}
       
    81 
       
    82 \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay}
       
    83 \date[] {10, October 2009\\Day 1, Session 4}
       
    84 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
    85 
       
    86 %\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo}
       
    87 %\logo{\pgfuseimage{iitmlogo}}
       
    88 
       
    89 
       
    90 %% Delete this, if you do not want the table of contents to pop up at
       
    91 %% the beginning of each subsection:
       
    92 \AtBeginSection[]
       
    93 {
       
    94   \begin{frame}<beamer>
       
    95     \frametitle{Outline}
       
    96     \tableofcontents[currentsection,subsections]
       
    97   \end{frame}
       
    98 }
       
    99 
       
   100 
       
   101 % If you wish to uncover everything in a step-wise fashion, uncomment
       
   102 % the following command: 
       
   103 %\beamerdefaultoverlayspecification{<+->}
       
   104 
       
   105 %\includeonlyframes{current,current1,current2,current3,current4,current5,current6}
       
   106 
       
   107 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
   108 % DOCUMENT STARTS
       
   109 \begin{document}
       
   110 
       
   111 \begin{frame}
       
   112   \titlepage
       
   113 \end{frame}
       
   114 
       
   115 \section{Advanced Data structures}
       
   116 
       
   117 \subsection{Dictionary}
       
   118 \begin{frame}{Dictionary}
       
   119   \begin{itemize}
       
   120     \item lists and tuples index: 0 \ldots n
       
   121     \item dictionaries index using strings
       
   122     \item \typ{ d = \{ ``Hitchhiker's guide'' : 42, ``Terminator'' : ``I'll be back''\}}
       
   123     \item \typ{d[``Terminator''] => ``I'll be back''}
       
   124     \item aka associative array, key-value pair, hashmap, hashtable \ldots    
       
   125     \item what can be keys?
       
   126   \end{itemize}
       
   127 \end{frame}
       
   128 
       
   129 \begin{frame}{Dictionary \ldots }
       
   130   \begin{itemize}
       
   131     \item \alert{Unordered}
       
   132       \begin{block}{Standard usage}
       
   133         for key in dict:\\
       
   134         \ \ \ \ print dict[key]
       
   135       \end{block}
       
   136     \item \typ{d.keys()} returns a list
       
   137     \item can we have duplicate keys?
       
   138   \end{itemize}
       
   139   \inctime{5}
       
   140 \end{frame}
       
   141 
       
   142 \begin{frame} {Problem Set 6.1}
       
   143   \begin{description}
       
   144 \item[6.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.
       
   145     \item[6.1.2] Count word frequencies in a file.
       
   146     \item[6.1.3] Find the most used Python keywords in your Python code (import keyword).
       
   147 \end{description}
       
   148 
       
   149 \inctime{10}
       
   150 \end{frame}
       
   151 
       
   152 \subsection{Set}
       
   153 \begin{frame}[fragile]
       
   154   \frametitle{Set}
       
   155     \begin{itemize}
       
   156       \item Simplest container, mutable
       
   157       \item No ordering, no duplicates
       
   158       \item usual suspects: union, intersection, subset \ldots
       
   159       \item >, >=, <, <=, in, \ldots
       
   160     \end{itemize}
       
   161     \begin{lstlisting}
       
   162 >>> f10 = set([1,2,3,5,8])
       
   163 >>> p10 = set([2,3,5,7])
       
   164 >>> f10|p10
       
   165 set([1, 2, 3, 5, 7, 8])
       
   166 >>> f10&p10
       
   167 set([2, 3, 5])
       
   168 >>> f10-p10
       
   169 set([8, 1])
       
   170 \end{lstlisting}
       
   171 \end{frame}
       
   172 
       
   173 \begin{frame}[fragile]
       
   174   \frametitle{Set}
       
   175     \begin{lstlisting}
       
   176 >>> p10-f10, f10^p10
       
   177 set([7]), set([1, 7, 8])
       
   178 >>> set([2,3]) < p10
       
   179 True
       
   180 >>> set([2,3]) <= p10
       
   181 True
       
   182 >>> 2 in p10
       
   183 True
       
   184 >>> 4 in p10
       
   185 False
       
   186 >>> len(f10)
       
   187 5
       
   188 \end{lstlisting}
       
   189 \inctime{5}
       
   190 \end{frame}
       
   191 
       
   192 \begin{frame}
       
   193   \frametitle{Problem set 6.2}
       
   194   \begin{description}
       
   195     \item[6.2.1] Given a dictionary of the names of students and their marks, identify how many duplicate marks are there? and what are these?
       
   196     \item[6.2.2] Given a string of the form ``4-7, 9, 12, 15'' find the numbers missing in this list for a given range.
       
   197 \end{description}
       
   198 \inctime{10}
       
   199 \end{frame}
       
   200 
       
   201 
       
   202 \section{Functions Reloaded!}
       
   203 \begin{frame}[fragile]
       
   204     \frametitle{Advanced functions}
       
   205     \begin{itemize}
       
   206         \item default args
       
   207         \item var args
       
   208         \item keyword args
       
   209         \item scope
       
   210         \item \typ{global}
       
   211       \end{itemize}
       
   212 \end{frame}
       
   213 
       
   214 \subsection{Default arguments}
       
   215 \begin{frame}[fragile]
       
   216   \frametitle{Functions: default arguments}
       
   217   \small
       
   218   \begin{lstlisting}
       
   219 def ask_ok(prompt, complaint='Yes or no!'):
       
   220     while True:
       
   221         ok = raw_input(prompt)
       
   222         if ok in ('y', 'ye', 'yes'): 
       
   223             return True
       
   224         if ok in ('n', 'no', 'nop',
       
   225                   'nope'): 
       
   226             return False
       
   227         print complaint
       
   228 
       
   229 ask_ok('?')
       
   230 ask_ok('?', '[Y/N]')
       
   231   \end{lstlisting}
       
   232 \end{frame}
       
   233 
       
   234 \subsection{Keyword arguments}
       
   235 \begin{frame}[fragile]
       
   236   \frametitle{Functions: keyword arguments}
       
   237   \small
       
   238   \begin{lstlisting}
       
   239 def ask_ok(prompt, complaint='Yes or no!'):
       
   240     while True:
       
   241         ok = raw_input(prompt)
       
   242         if ok in ('y', 'ye', 'yes'): 
       
   243             return True
       
   244         if ok in ('n', 'no', 'nop',
       
   245                   'nope'): 
       
   246             return False
       
   247         print complaint
       
   248 
       
   249 ask_ok(prompt='?')
       
   250 ask_ok(prompt='?', complaint='[y/n]')
       
   251 ask_ok(complaint='[y/n]', prompt='?')
       
   252 \end{lstlisting}
       
   253 \inctime{15} 
       
   254 \end{frame}
       
   255 
       
   256 \section{Functional programming}
       
   257 \begin{frame}[fragile]
       
   258     \frametitle{Functional programming}
       
   259     \begin{itemize}
       
   260       \item What is the basic idea?
       
   261       \item Why is it interesting?
       
   262       \item \typ{map, reduce, filter}
       
   263       \item list comprehension
       
   264       \item generators
       
   265     \end{itemize}
       
   266 \end{frame}
       
   267 
       
   268 \subsection{List comprehensions}
       
   269 \begin{frame}[fragile]
       
   270     \frametitle{List Comprehensions}
       
   271 Lets say we want to squares of all the numbers from 1 to 100
       
   272     \begin{lstlisting}
       
   273 squares = []
       
   274 for i in range(1, 100):
       
   275     squares.append(i * i)
       
   276     \end{lstlisting}
       
   277     \begin{lstlisting}
       
   278 # list comprehension
       
   279 squares = [i*i for i in range(1, 100)]
       
   280      \end{lstlisting}
       
   281 Which is more readable?
       
   282 \end{frame}
       
   283 
       
   284 \begin{frame}[fragile]
       
   285     \frametitle{List Comprehensions}
       
   286 What if you had a more complex function?
       
   287 Lets say we want squares of numbers from 1 to 100 ending in 1, 2, 5, 7 only
       
   288     \begin{lstlisting}
       
   289 squares = []
       
   290 for i in range(1, 100):
       
   291     if i % 10 in [1, 2, 5, 7]:
       
   292         squares.append(i * i)
       
   293     \end{lstlisting}
       
   294     \begin{lstlisting}
       
   295 # list comprehension
       
   296 squares = [i*i for i in range(1, 100)
       
   297            if i % 10 in [1, 2, 5, 7]]
       
   298      \end{lstlisting}
       
   299 Which is more readable?
       
   300 \inctime{15}
       
   301 \end{frame}
       
   302 
       
   303 \section{Debugging}
       
   304 \subsection{Errors and Exceptions}
       
   305 \begin{frame}[fragile]
       
   306  \frametitle{Errors}
       
   307  \begin{lstlisting}
       
   308 >>> while True print 'Hello world'
       
   309  \end{lstlisting}
       
   310 \pause
       
   311   \begin{lstlisting}
       
   312   File "<stdin>", line 1, in ?
       
   313     while True print 'Hello world'
       
   314                    ^
       
   315 SyntaxError: invalid syntax
       
   316 \end{lstlisting}
       
   317 \end{frame}
       
   318 
       
   319 \begin{frame}[fragile]
       
   320  \frametitle{Exceptions}
       
   321  \begin{lstlisting}
       
   322 >>> print spam
       
   323 \end{lstlisting}
       
   324 \pause
       
   325 \begin{lstlisting}
       
   326 Traceback (most recent call last):
       
   327   File "<stdin>", line 1, in <module>
       
   328 NameError: name 'spam' is not defined
       
   329 \end{lstlisting}
       
   330 \end{frame}
       
   331 
       
   332 \begin{frame}[fragile]
       
   333  \frametitle{Exceptions}
       
   334  \begin{lstlisting}
       
   335 >>> 1 / 0
       
   336 \end{lstlisting}
       
   337 \pause
       
   338 \begin{lstlisting}
       
   339 Traceback (most recent call last):
       
   340   File "<stdin>", line 1, in <module>
       
   341 ZeroDivisionError: integer division 
       
   342 or modulo by zero
       
   343 \end{lstlisting}
       
   344 \end{frame}
       
   345 
       
   346 \subsection{Strategy}
       
   347 \begin{frame}[fragile]
       
   348     \frametitle{Debugging effectively}
       
   349     \begin{itemize}
       
   350         \item \kwrd{print} based strategy
       
   351         \item Process:
       
   352     \end{itemize}
       
   353 \pgfimage[interpolate=true,width=5cm,height=5cm]{DebugginDiagram.png}
       
   354 \end{frame}
       
   355 
       
   356 \begin{frame}[fragile]
       
   357     \frametitle{Debugging effectively}
       
   358     \begin{itemize}
       
   359       \item Using \typ{\%debug} in IPython
       
   360     \end{itemize}
       
   361 \end{frame}
       
   362 
       
   363 \begin{frame}[fragile]
       
   364 \frametitle{Debugging in IPython}
       
   365 \small
       
   366 \begin{lstlisting}
       
   367 In [1]: import mymodule
       
   368 In [2]: mymodule.test()
       
   369 ---------------------------------------------
       
   370 NameError   Traceback (most recent call last)
       
   371 <ipython console> in <module>()
       
   372 mymodule.py in test()
       
   373       1 def test():
       
   374 ----> 2     print spam
       
   375 NameError: global name 'spam' is not defined
       
   376 
       
   377 In [3]: %debug
       
   378 > mymodule.py(2)test()
       
   379       0     print spam
       
   380 ipdb> 
       
   381 \end{lstlisting}
       
   382 \inctime{15} 
       
   383 \end{frame}
       
   384 
       
   385 \subsection{Exercise}
       
   386 \begin{frame}[fragile]
       
   387 \frametitle{Debugging: Exercise}
       
   388 \small
       
   389 \begin{lstlisting}
       
   390 import keyword
       
   391 f = open('/path/to/file')
       
   392 
       
   393 freq = {}
       
   394 for line in f:
       
   395     words = line.split()
       
   396     for word in words:
       
   397         key = word.strip(',.!;?()[]: ')
       
   398         if keyword.iskeyword(key):
       
   399             value = freq[key]
       
   400             freq[key] = value + 1
       
   401 
       
   402 print freq
       
   403 \end{lstlisting}
       
   404 \inctime{10}
       
   405 \end{frame}
       
   406 
       
   407 \begin{frame}
       
   408   \frametitle{What did we learn?}
       
   409   \begin{itemize}
       
   410     \item Dictionaries
       
   411     \item Sets
       
   412     \item Default and keyword arguments
       
   413     \item Functional Programming, list comprehensions
       
   414     \item Errors and Exceptions in Python
       
   415     \item Debugging: \%debug in IPython
       
   416   \end{itemize}
       
   417 \end{frame}
       
   418 \end{document}