# HG changeset patch # User Madhusudan.C.S # Date 1255504401 -19800 # Node ID 24992ab48f2bed2e1240fd41f6e7964e9b7feb66 # Parent ae070c1331201d878e767e794fd8a8d3f9ec98de Created the pristine form of the repository for Goa workshop. diff -r ae070c133120 -r 24992ab48f2b day1/BasicPython.tex --- a/day1/BasicPython.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,2745 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2008, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -%\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\texttt{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -%%% This is from Fernando's setup. -% \usepackage{color} -% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} -% % Use and configure listings package for nicely formatted code -% \usepackage{listings} -% \lstset{ -% language=Python, -% basicstyle=\small\ttfamily, -% commentstyle=\ttfamily\color{blue}, -% stringstyle=\ttfamily\color{orange}, -% showstringspaces=false, -% breaklines=true, -% postbreak = \space\dots -% } - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Python:\\A great programming toolkit} - -\author[Asokan \& Prabhu] {Asokan Pichai\\Prabhu Ramachandran} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {25, July 2009} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} -%\logo{\pgfuseimage{iitmlogo}} - - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each subsection: -\AtBeginSubsection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - - -% If you wish to uncover everything in a step-wise fashion, uncomment -% the following command: -%\beamerdefaultoverlayspecification{<+->} - -%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \titlepage -\end{frame} -\begin{frame} - {Acknowledgements} - \begin{center} - This program is conducted by\\ - IIT, Bombay\\ - through CDEEP\\as part of the open source initiatives\\ - under the aegis of\\ - \alert{National Mission on Education through ICT,} \\ - Ministry of HRD. - \end{center} -\end{frame} - -\begin{frame} - \frametitle{Outline} - \tableofcontents - % You might wish to add the option [pausesections] -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TODO -% -% * Add slide on Python packages (modules) -% * Add slides on reference counting. - -\section{Agenda} -\begin{frame}{About the Workshop} - \begin{description} - \item[Session 1] Sat 14:00--15:55 - \item[Session 2] Sat 16:05--18:00 - \item[Session 3] Sun 14:00--15:55 - \item[Session 4] Sun 16:05--18:00 - \end{description} - - \begin{block}{Goal of the workshop} - At the end of this program, successful participants will be able to use python as their scripting and problem solving language. Aimed at Engg. students--focus on basic numerics and plotting-- but should serve a similar purpose for others. - \end{block} -\end{frame} - -\begin{frame}{Checklist} - Let us verify that all of us are having the same (similar) tools and environment - \begin{description} - \item[python] Type python at the command line. Do you see version 2.5 or later? - \item[IPython] Is IPython available? - \item[Editor] Which editor? scite, vim, emacs, \ldots - \end{description} -\end{frame} - -\section{Overview} -\begin{frame}{Session 1} - \begin{itemize} - \item Introduction and motivation - \item Using the interpreter(s) - \item Basic data types: int, float, string - \item Basic data structures: list - \item Basic console IO: \texttt{raw\_input(), print} - \item Basic control flow: \texttt{if, while} - \item Problem set 1 - \item Functions $\rightarrow$ Problem set 2 - \item lists, \texttt{for} $\rightarrow$ Problem set 3 - \item IO, Modules $\rightarrow$ Problem sets 4,5, \ldots - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Introduction} - \begin{itemize} - \item Creator and BDFL: Guido van Rossum - \item Conceived in December 1989 - \item ``Python'' as in Monty Python's Flying Circus - \item Current stable version of Python is 2.6.x - \item PSF license (like BSD: no strings attached) - \item Highly cross platform - \item Runs on the Nokia series 60! - \item \alert{Philosophy:} Simple and complete by design - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Resources} - \begin{itemize} - \item Part of many GNU/Linux distributions - \item Web: \url{http://www.python.org} - \item Doc: \url{http://www.python.org/doc} - \item Free Tutorials: - \begin{itemize} - \item Official Python tutorial: \url{http://docs.python.org/tut/tut.html} - \item Byte of Python: \url{http://www.byteofpython.info/} - \item Dive into Python: \url{http://diveintopython.org/} - \end{itemize} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Why Python?} - \begin{itemize} - \item Designed to be readable and easy to use - \item High level, interpreted, modular, OO - \item Much faster development cycle - \item Powerful interactive environment - \item Rapid application development - \item Rich standard library and modules - \item Interfaces well with C++, C and FORTRAN - \item \alert{More than a math package $\Rightarrow$ some extra work compared to math packages} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Use cases} - \begin{itemize} - \item NASA: Space Shuttle Mission Design - \item AstraZeneca: Collaborative Drug Discovery - \item ForecastWatch.com: Helps Meteorologists - \item Industrial Light \& Magic: Runs on Python - \item Zope: Commercial grade Toolkit - \item Plone: Professional high feature CMS - \item RedHat: install scripts, sys-admin tools - \item Django: A great web application framework - \item Google: A strong python shop - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{To sum up, python is\ldots} - \begin{itemize} - \item dynamically typed, interpreted $\rightarrow$ rapid testing/prototyping - \item powerful, very high level - \item has full introspection - \item Did we mention powerful? - \end{itemize} - \begin{block}{But \ldots} - may be wanting in performance. specialised resources such as SWIG, \alert{Cython} are available - \end{block} - \inctime{15} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 15 m, running 15m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{Python} - -\subsection{Getting Started} - -\begin{frame}[fragile]{At the prompt, type the following} - \begin{lstlisting} ->>> print 'Hello Python' ->>> print 3124 * 126789 ->>> 1786 % 12 ->>> 3124 * 126789 ->>> a = 3124 * 126789 ->>> big = 12345678901234567890 ** 3 ->>> verybig = big * big * big * big ->>> 12345**6, 12345**67, 12345**678 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile]{At the prompt, type the following} - \begin{lstlisting} ->>> s = 'Hello ' ->>> p = 'World' ->>> s + p ->>> s * 12 ->>> s * s ->>> s + p * 12, (s + p)* 12 ->>> s * 12 + p * 12 ->>> 12 * s - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile]{At the prompt, type the following} - \begin{lstlisting} ->>> 17/2 ->>> 17/2.0 ->>> 17.0/2 ->>> 17.0/8.5 ->>> int(17/2.0) ->>> float(17/2) ->>> str(17/2.0) ->>> round( 7.5 ) - \end{lstlisting} - \begin{block}{Mini exercise} - Round a float to the nearest integer, using \texttt{int()}? - \end{block} -\end{frame} - -\begin{frame}{Midi exercises} - \begin{center} - \begin{itemize} - \item What does this do? - \item \texttt{round(amount * 10) /10.0 } - \end{itemize} - \end{center} -\end{frame} - -\begin{frame}{More exercises?} - \begin{center} - \begin{block}{Round sums} - How to round a number to the nearest 5 paise?\\ - \begin{description} - \item[Remember] 17.23 $\rightarrow$ 17.25,\\ while 17.22 $\rightarrow$ 17.20\\ - \end{description} - How to round a number to the nearest 20 paise? - \end{block} - \end{center} -\end{frame} - -\begin{frame}[fragile] {A question of good style} - \begin{lstlisting} - amount = 12.68 - denom = 0.05 - nCoins = round(amount/denom) - rAmount = nCoins * denom - \end{lstlisting} - \pause - \begin{block}{Style Rule \#1} - Naming is 80\% of programming - \end{block} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Odds and ends} - \begin{itemize} - \item Case sensitive - \item Dynamically typed $\Rightarrow$ need not specify a type - \begin{lstlisting} -a = 1 -a = 1.1 -a = "Now I am a string!" - \end{lstlisting} - \item Comments: - \begin{lstlisting} -a = 1 # In-line comments -# Comment in a line to itself. -a = "# This is not a comment!" - \end{lstlisting} - \end{itemize} - \inctime{15} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 15 m, running 30m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\subsection{Data types} -\begin{frame} - \frametitle{Basic types} - \begin{itemize} - \item numbers: float, int, long, complex - \item strings - \item boolean - \end{itemize} - \begin{block}{Also to be discussed later} - tuples, lists, dictionaries, functions, objects\ldots - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Numbers} - \vspace*{-0.25in} - \begin{lstlisting} ->>> a = 1 # Int. ->>> l = 1000000L # Long ->>> e = 1.01325e5 # float ->>> f = 3.14159 # float ->>> c = 1+1j # Complex! ->>> print f*c/a -(3.14159+3.14159j) ->>> print c.real, c.imag -1.0 1.0 ->>> abs(c) -1.4142135623730951 ->>> abs( 8 - 9.5 ) -1.5 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Boolean} - \begin{lstlisting} ->>> t = True ->>> f = not t -False ->>> f or t -True ->>> f and t -False - \end{lstlisting} - \begin{block}{Try:} - NOT True\\ - not TRUE - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Relational and logical operators} - \begin{lstlisting} ->>> a, b, c = -1, 0, 1 ->>> a == b -False ->>> a <= b -True ->>> a + b != c -True ->>> a < b < c -True ->>> c >= a + b -True - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Strings} - \begin{lstlisting} -s = 'this is a string' -s = 'This one has "quotes" inside!' -s = "I have 'single-quotes' inside!" -l = "A string spanning many lines\ -one more line\ -yet another" -t = """A triple quoted string does -not need to be escaped at the end and -"can have nested quotes" etc.""" - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More Strings} - \vspace*{-0.2in} - \begin{lstlisting} ->>> w = "hello" ->>> print w[0] + w[2] + w[-1] -hlo ->>> len(w) # guess what -5 ->>> s = u'Unicode strings!' ->>> # Raw strings (note the leading 'r') -... r_s = r'A string $\alpha \nu$' - \end{lstlisting} -\pause - \begin{lstlisting} ->>> w[0] = 'H' # Can't do that! -Traceback (most recent call last): - File "", line 1, in ? -TypeError: object does not support item assignment - \end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Let us switch to IPython} - Why? - \begin{block} - {Better help (and a lot more)} - Tab completion\\ - ?\\ - .?\\ - object.function? - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More on strings} - \begin{lstlisting} -In [1]: a = 'hello world' -In [2]: a.startswith('hell') -Out[2]: True -In [3]: a.endswith('ld') -Out[3]: True -In [4]: a.upper() -Out[4]: 'HELLO WORLD' -In [5]: a.upper().lower() -Out[5]: 'hello world' - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile]{Still with strings} - \begin{lstlisting} -In [6]: a.split() -Out[6]: ['hello', 'world'] -In [7]: ''.join(['a', 'b', 'c']) -Out[7]: 'abc' -In [8] 'd' in ''.join( 'a', 'b', 'c') -Out[8]: False - \end{lstlisting} - \begin{block}{Try:} - \texttt{a.split( 'o' )}\\ - \texttt{'x'.join( a.split( 'o' ) )} - \end{block} -\end{frame} - -\begin{frame}[fragile]{Surprise! strings!!} - \begin{lstlisting} -In [11]: x, y = 1, 1.2 -In [12]: 'x is %s, y is %s' %(x, y) -Out[12]: 'x is 1, y is 1.234' - \end{lstlisting} - \begin{block}{Try:} - \texttt{'x is \%d, y is \%f' \%(x, y) }\\ - \texttt{'x is \%3d, y is \%4.2f' \%(x, y) } - \end{block} - \small -\url{docs.python.org/lib/typesseq-strings.html}\\ -\end{frame} - -\begin{frame} - {Interlude} - \begin{block} - {A classic problem} - How to interchange values of two variables? Please note that the type of either variable is unknown and it is not necessary that both be of the same type even! - \end{block} - \inctime{30} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 25 m+ Interlude break 5 mins, running 60m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\subsection{Control flow} -\begin{frame} - \frametitle{Control flow constructs} - \begin{itemize} - \item \kwrd{if/elif/else}: branching - \item \kwrd{while}: looping - \item \kwrd{for}: iterating - \item \kwrd{break, continue}: modify loop - \item \kwrd{pass}: syntactic filler - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic conditional flow} - \begin{lstlisting} -In [21]: a = 7 -In [22]: b = 8 -In [23]: if a > b: - ....: print 'Hello' - ....: else: - ....: print 'World' - ....: - ....: -World - \end{lstlisting} - Let us switch to creating a file -\end{frame} - -\begin{frame} - {Creating python files} - \begin{itemize} - \item aka scripts - \item use your editor - \item Note that white space is the way to specify blocks! - \item extension \typ{.py} - \item run with \texttt{python hello.py} at the command line - \item in IPython\ldots - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{If...elif...else} example} -\begin{lstlisting} -x = int(raw_input("Enter an integer:")) -if x < 0: - print 'Be positive!' -elif x == 0: - print 'Zero' -elif x == 1: - print 'Single' -else: - print 'More' -\end{lstlisting} -\end{frame} - -\begin{frame}{Simple IO} - \begin{block} - {Console Input} - \texttt{raw\_input(}) waits for user input.\\Prompt string is optional.\\ - All keystrokes are Strings!\\\texttt{int()} converts string to int. - \end{block} - \begin{block} - {Console output} - \texttt{print} is straight forward. Major point to remember is the distinction between \texttt{print x} and \texttt{print x,} - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic looping} - \begin{lstlisting} -# Fibonacci series: -# the sum of two elements -# defines the next -a, b = 0, 1 -while b < 10: - print b, - a, b = b, a + b - -\end{lstlisting} -\typ{1 1 2 3 5 8}\\ -\alert{Recall it is easy to write infinite loops with \kwrd{while}} - \inctime{20} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 20 m, running 80m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\begin{frame} - \frametitle{Problem set 1} - \begin{itemize} - \item All the problems can be\\ - solved using \kwrd{if} and \kwrd{while} - \end{itemize} -\end{frame} - -\begin{frame}{Problem 1.1} - Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ -These are called $Armstrong$ numbers. -\end{frame} - -\begin{frame}{Problem 1.2 - Collatz sequence} -\begin{enumerate} - \item Start with an arbitrary (positive) integer. - \item If the number is even, divide by 2; if the number is odd multiply by 3 and add 1. - \item Repeat the procedure with the new number. - \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. -\end{enumerate} - Write a program that accepts the starting value and prints out the Collatz sequence. - -\end{frame} - -\begin{frame}{Problem 1.3 - Kaprekar's constant} - \begin{enumerate} - \item Take a four digit number--with at least two digits different. - \item Arrange the digits in ascending and descending order, giving A and D respectively. - \item Leave leading zeros in A! - \item Subtract A from D. - \item With the result, repeat from step 2. - \end{enumerate} - Write a program to accept a 4-digit number and display the progression to Kaprekar's constant. -\end{frame} - -\begin{frame}[fragile]{Problem 1.4} - Write a program that prints the following pyramid on the screen. - \begin{lstlisting} -1 -2 2 -3 3 3 -4 4 4 4 - \end{lstlisting} -The number of lines must be obtained from the user as input.\\ -\pause -When can your code fail? -\only<2->{\inctime{25}} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 25 m, running 105m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\subsection{Functions} -\begin{frame}[fragile] -\frametitle{Functions: examples} - \begin{lstlisting} -def signum( r ): - """returns 0 if r is zero - -1 if r is negative - +1 if r is positive""" - if r < 0: - return -1 - elif r > 0: - return 1 - else: - return 0 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Functions: examples} - \begin{lstlisting} -def pad( n, size ): - """pads integer n with spaces - into a string of length size - """ - SPACE = ' ' - s = str( n ) - padSize = size - len( s ) - return padSize * SPACE + s - \end{lstlisting} -\pause -What about \%3d? -\end{frame} - -\begin{frame}[fragile] - {What does this function do?} - \begin{lstlisting} -def what( n ): - if n < 0: n = -n - while n > 0: - if n % 2 == 1: - return False - n /= 10 - return True - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - {What does this function do?} -\begin{lstlisting} -def what( n ): - i = 1 - while i * i < n: - i += 1 - return i * i == n, i - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - {What does this function do?} - \begin{lstlisting} -def what( n, x ): - z = 1.0 - if n < 0: - x = 1.0 / x - n = -n - while n > 0: - if n % 2 == 1: - z *= x - n /= 2 - x *= x - return z - \end{lstlisting} -\end{frame} - -\begin{frame} - {Before writing a function} - \begin{itemize} - \item Builtin functions for various and sundry - \item \typ{abs, any, all, len, max, min} - \item \typ{pow, range, sum, type} - \item Refer here: - \url{http://docs.python.org/library/functions.html} - \end{itemize} - \inctime{15} -\end{frame} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 15 m, running 120m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\begin{frame}{Problem set 2} - The focus is on writing functions and calling them. -\end{frame} - -\begin{frame}{Problem 2.1} - Write a function to return the gcd of two numbers. -\end{frame} - -\begin{frame}{Problem 2.2} -A pythagorean triad $(a,b,c)$ has the property $a^2 + b^2 = c^2$.\\By primitive we mean triads that do not `depend' on others. For example, (4,3,5) is a variant of (3,4,5) and hence is not primitive. And (10,24,26) is easily derived from (5,12,13) and should not be displayed by our program. \\ -Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100 -\end{frame} - -\begin{frame}{Problem 2.3} - Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\\For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square). -\end{frame} - -\begin{frame}{Problem 2.4} - The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. For example, the aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.\\ - Write a function that returns the aliquot number of a given number. -\end{frame} - -\begin{frame}{Problem 2.5} - A pair of numbers (a, b) is said to be \alert{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ - Example: \texttt{220, 284}\\ - Write a program that prints all five digit amicable pairs. - \inctime{30} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 30 m, running 150m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\subsection{Lists} - -\begin{frame}[fragile] - \frametitle{List creation and indexing} -\begin{lstlisting} ->>> a = [] # An empty list. ->>> a = [1, 2, 3, 4] # More useful. ->>> len(a) -4 ->>> a[0] + a[1] + a[2] + a[-1] -10 -\end{lstlisting} - \begin{itemize} - \item Indices start with ? - \item Negative indices indicate ? - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{List: slices} - \begin{itemize} - \item Slicing is a basic operation - \item \typ{list[initial:final:step]} - \item The step is optional - \end{itemize} -\begin{lstlisting} ->>> a[1:3] # A slice. -[2, 3] ->>> a[1:-1] -[2, 3, 4] ->>> a[1:] == a[1:-1] -False -\end{lstlisting} -Explain last result -\end{frame} - -\begin{frame}[fragile] - \frametitle{List: more slices} -\begin{lstlisting} ->>> a[0:-1:2] # Notice the step! -[1, 3] ->>> a[::2] -[1, 3] ->>> a[-1::-1] -\end{lstlisting} -What do you think the last one will do? - \emphbar{Note: Strings also use same indexing and slicing.} -\end{frame} - -\begin{frame}[fragile] - \frametitle{List: examples} -\begin{lstlisting} ->>> a = [1, 2, 3, 4] ->>> a[:2] -[1, 3] ->>> a[0:-1:2] -[1, 3] -\end{lstlisting} -\pause -\alert{Lists are mutable (unlike strings)} -\begin{lstlisting} ->>> a[1] = 20 ->>> a -[1, 20, 3, 4] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Lists are mutable and heterogenous} -\begin{lstlisting} ->>> a = ['spam', 'eggs', 100, 1234] ->>> a[2] = a[2] + 23 ->>> a -['spam', 'eggs', 123, 1234] ->>> a[0:2] = [1, 12] # Replace items ->>> a -[1, 12, 123, 1234] ->>> a[0:2] = [] # Remove items ->>> a.append( 12345 ) ->>> a -[123, 1234, 12345] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{List methods} -\begin{lstlisting} ->>> a = ['spam', 'eggs', 1, 12] ->>> a.reverse() # in situ ->>> a -[12, 1, 'eggs', 'spam'] ->>> a.append(['x', 1]) ->>> a -[12, 1, 'eggs', 'spam', ['x', 1]] ->>> a.extend([1,2]) # Extend the list. ->>> a.remove( 'spam' ) ->>> a -[12, 1, 'eggs', ['x', 1], 1, 2] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{List containership} - \begin{lstlisting} ->>> a = ['cat', 'dog', 'rat', 'croc'] ->>> 'dog' in a -True ->>> 'snake' in a -False ->>> 'snake' not in a -True ->>> 'ell' in 'hello world' -True - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Tuples: immutable} -\begin{lstlisting} ->>> t = (0, 1, 2) ->>> print t[0], t[1], t[2], t[-1] -0 1 2 2 ->>> t[0] = 1 -Traceback (most recent call last): - File "", line 1, in ? -TypeError: object does not support item - assignment -\end{lstlisting} -\begin{itemize} - \item Multiple return values are actually a tuple. - \item Exchange is tuple (un)packing -\end{itemize} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{range()} function} - \begin{lstlisting} ->>> range(7) -[0, 1, 2, 3, 4, 5, 6] ->>> range( 3, 9) -[3, 4, 5, 6, 7, 8] ->>> range( 4, 17, 3) -[4, 7, 10, 13, 16] ->>> range( 5, 1, -1) -[5, 4, 3, 2] ->>> range( 8, 12, -1) -[] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{for\ldots range(\ldots)} idiom} - \begin{lstlisting} -In [83]: for i in range(5): - ....: print i, i * i - ....: - ....: -0 0 -1 1 -2 4 -3 9 -4 16 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{for}: the list companion} - - \begin{lstlisting} -In [84]: a = ['a', 'b', 'c'] -In [85]: for x in a: - ....: print x, chr( ord(x) + 10 ) - ....: -a k -b l -c m - \end{lstlisting} - Iterating over the list and not the index + reference\\ - what if you want the index? -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{for}: the list companion} - \begin{lstlisting} -In [89]: for p, ch in enumerate( a ): - ....: print p, ch - ....: - ....: -0 a -1 b -2 c - \end{lstlisting} -Try: \typ{print enumerate(a)} -\inctime{20} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 20 m, running 170m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\begin{frame} - {Problem set 3} - As you can guess, idea is to use \kwrd{for}! -\end{frame} - -\begin{frame}{Problem 3.1} - Which of the earlier problems is simpler when we use \kwrd{for} instead of \kwrd{while}? -\end{frame} - -\begin{frame}{Problem 3.2} - Given an empty chessboard and one Bishop placed in any square, say (r, c), generate the list of all squares the Bishop could move to. -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem 3.3} - - Given two real numbers \typ{a, b}, and an integer \typ{N}, write a - function named \typ{linspace( a, b, N)} that returns an ordered list - of \typ{N} points starting with \typ{a} and ending in \typ{b} and - equally spaced.\\ - - For example, \typ{linspace(0, 5, 11)}, should return, \\ -\begin{lstlisting} -[ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, - 3.0 , 3.5, 4.0 , 4.5, 5.0 ] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem 3.4a (optional)} - -Use the \typ{linspace} function and generate a list of N tuples of the form\\ -\typ{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions,\begin{itemize} - \item \typ{f(x) = sin(x)} - \item \typ{f(x) = sin(x) + sin(10*x)}. -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem 3.4b (optional)} - - Using the tuples generated earlier, determine the intervals where the roots of the functions lie. - - \inctime{15} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 15 m, running 185m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\subsection{IO} - -\begin{frame}[fragile] - \frametitle{Simple tokenizing and parsing} - \begin{lstlisting} -s = """The quick brown fox jumped - over the lazy dog""" -for word in s.split(): - print word.capitalize() - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem 4.1} - Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \\ - \begin{lstlisting} - [1,3,4,5,6,7,12,15,18,19,20,21] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{File handling} -\begin{lstlisting} ->>> f = open('/path/to/file_name') ->>> data = f.read() # Read entire file. ->>> line = f.readline() # Read one line. ->>> f.close() # close the file. -\end{lstlisting} -Writing files -\begin{lstlisting} ->>> f = open('/path/to/file_name', 'w') ->>> f.write('hello world\n') ->>> f.close() -\end{lstlisting} -\begin{itemize} - \item Everything read or written is a string -\end{itemize} -\emphbar{Try \typ{file?} for more help} -\end{frame} - -\begin{frame}[fragile] - \frametitle{File and \kwrd{for}} -\begin{lstlisting} ->>> f = open('/path/to/file_name') ->>> for line in f: -... print line -... -\end{lstlisting} -\end{frame} - -\begin{frame}{Problem 4.2} - The given file has lakhs of records in the form:\\ - \typ{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}\\ - Some entries may be empty. Read the data from this file and print the - name of the student with the maximum total marks. -\end{frame} - -\begin{frame}{Problem 4.3} - For the same data file compute the average marks in different - subjects, the student with the maximum mark in each subject and also - the standard deviation of the marks. Do this efficiently. - - \inctime{20} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 20 m, running 205m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\subsection{Modules} - -\begin{frame}[fragile] - {Modules} -\begin{lstlisting} ->>> sqrt(2) -Traceback (most recent call last): - File "", line 1, in -NameError: name 'sqrt' is not defined ->>> import math ->>> math.sqrt(2) -1.4142135623730951 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - {Modules} - \begin{itemize} - \item The \kwrd{import} keyword ``loads'' a module - \item One can also use: - \begin{lstlisting} ->>> from math import sqrt ->>> from math import * - \end{lstlisting} - \item What is the difference? - \item \alert{Use the later only in interactive mode} - \end{itemize} - \emphbar{Package hierarchies} - \begin{lstlisting} ->>> from os.path import exists - \end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Modules: Standard library} - \begin{itemize} - \item Very powerful, ``Batteries included'' - \item Some standard modules: - \begin{itemize} - \item Math: \typ{math}, \typ{random} - \item Internet access: \typ{urllib2}, \typ{smtplib} - \item System, Command line arguments: \typ{sys} - \item Operating system interface: \typ{os} - \item Regular expressions: \typ{re} - \item Compression: \typ{gzip}, \typ{zipfile}, and \typ{tarfile} - \item And a whole lot more! - \end{itemize} - \item Check out the Python Library reference: - \url{http://docs.python.org/library/} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - {Modules of special interest} - \begin{description}[matplotlibfor2d] - - \item[\typ{numpy}] Efficient, powerful numeric arrays - - \item[\typ{matplotlib}] Easy, interactive, 2D plotting - - \item[\typ{scipy}] statistics, optimization, integration, linear - algebra, Fourier transforms, signal and image processing, - genetic algorithms, ODE solvers, special functions, and more - - \item[Mayavi] Easy, interactive, 3D plotting - - \end{description} -\end{frame} - -\begin{frame}[fragile] - {Creating your own modules} - \begin{itemize} - \item Define variables, functions and classes in a file with a - \typ{.py} extension - \item This file becomes a module! - \item Accessible when in the current directory - \item Use \typ{cd} in IPython to change directory - - \item Naming your module - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Modules: example} - \begin{lstlisting} -# --- arith.py --- -def gcd(a, b): - if a%b == 0: return b - return gcd(b, a%b) -def lcm(a, b): - return a*b/gcd(a, b) -# ------------------ ->>> import arith ->>> arith.gcd(26, 65) -13 ->>> arith.lcm(26, 65) -130 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem 5.1} - - Put all the functions you have written so far as part of the problems - into one module called \typ{iitb.py} and use this module from IPython. - -\inctime{20} -\end{frame} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 20 m, running 225m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\begin{frame} - \frametitle{Did we meet the goal?} - \tableofcontents - % You might wish to add the option [pausesections] - \end{frame} - - \begin{frame} - {Tomorrow} - \begin{itemize} - \item Plotting: 2D, 3D - \item NumPy, SciPy - \item Dictionary, Set - \item Debugging - \item Testing - \item \ldots - \end{itemize} - 11:30--13:00 Discussion of answers to problems OPTIONAL - \end{frame} -\end{document} - - -\begin{frame}[fragile] - \frametitle{More on functions} - \begin{itemize} - \item Support default and keyword arguments - \item Scope of variables in the function is local - \item Mutable items are \alert{passed by reference} - \item First line after definition may be a documentation string - (\alert{recommended!}) - \item Function definition and execution defines a name bound to the - function - \item You \emph{can} assign a variable to a function! - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Functions: default arguments} - \begin{lstlisting} -def ask_ok(prompt, retries=4, complaint='Yes or no!'): - while True: - ok = raw_input(prompt) - if ok in ('y', 'ye', 'yes'): - return True - if ok in ('n', 'no', 'nop', 'nope'): - return False - retries = retries - 1 - if retries < 0: - raise IOError, 'bad user' - print complaint - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Functions: keyword arguments} - \begin{lstlisting} -def parrot(voltage, state='a stiff', - action='voom', type='Norwegian Blue'): - print "-- This parrot wouldn't", action, - print "if you put", voltage, "Volts through it." - print "-- Lovely plumage, the", type - print "-- It's", state, "!" - -parrot(1000) -parrot(action = 'VOOOOOM', voltage = 1000000) -parrot('a thousand', state = 'pushing up the daisies') -parrot('a million', 'bereft of life', 'jump') -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Functions: arbitrary argument lists} - \begin{itemize} - \item Arbitrary number of arguments using \verb+*args+ or - \verb+*whatever+ - \item Keyword arguments using \verb+**kw+ - \item Given a tuple/dict how do you call a function? - \begin{itemize} - \item Using argument unpacking - \item For positional arguments: \verb+foo(*[5, 10])+ - \item For keyword args: \verb+foo(**{'a':5, 'b':10})+ - \end{itemize} - \end{itemize} -\begin{lstlisting} -def foo(a=10, b=100): - print a, b -def func(*args, **keyword): - print args, keyword -# Unpacking: -args = [5, 10] -foo(*args) -kw = {'a':5, 'b':10} -foo(**kw) -\end{lstlisting} -\end{frame} - -\subsection{Modules, exceptions, classes} - -\begin{frame} - \frametitle{Modules} - \begin{itemize} - \item Define variables, functions and classes in a file with a - \typ{.py} extension - \item This file becomes a module! - \item Modules are searched in the following: - \begin{itemize} - \item Current directory - \item Standard: \typ{/usr/lib/python2.3/site-packages/} etc. - \item Directories specified in PYTHONPATH - \item \typ{sys.path}: current path settings (from the \typ{sys} - module) - \end{itemize} - \item The \typ{import} keyword ``loads'' a module - \item One can also use: - \mbox{\typ{from module import name1, name2, name2}}\\ - where \typ{name1} etc. are names in the module, ``module'' - \item \typ{from module import *} \ --- imports everything from module, - \alert{use only in interactive mode} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Modules: example} - \begin{lstlisting} -# --- foo.py --- -some_var = 1 -def fib(n): # write Fibonacci series up to n - """Print a Fibonacci series up to n.""" - a, b = 0, 1 - while b < n: - print b, - a, b = b, a+b -# EOF - ->>> import foo ->>> foo.fib(10) -1 1 2 3 5 8 ->>> foo.some_var -1 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Namespaces} - \begin{itemize} - \item A mapping from names to objects - \item Modules introduce a namespace - \item So do classes - \item The running script's namespace is \verb+__main__+ - \item A modules namespace is identified by its name - \item The standard functions (like \typ{len}) are in the - \verb+__builtin__+ namespace - \item Namespaces help organize different names and their bindings to - different objects - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Exceptions} - \begin{itemize} - \item Python's way of notifying you of errors - \item Several standard exceptions: \typ{SyntaxError}, \typ{IOError} - etc. - \item Users can also \typ{raise} errors - \item Users can create their own exceptions - \item Exceptions can be ``caught'' via \typ{try/except} blocks - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exception: examples} -\begin{lstlisting} ->>> 10 * (1/0) -Traceback (most recent call last): - File "", line 1, in ? -ZeroDivisionError: integer division or modulo by zero ->>> 4 + spam*3 -Traceback (most recent call last): - File "", line 1, in ? -NameError: name 'spam' is not defined ->>> '2' + 2 -Traceback (most recent call last): - File "", line 1, in ? -TypeError: cannot concatenate 'str' and 'int' objects -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exception: examples} -\begin{lstlisting} ->>> while True: -... try: -... x = int(raw_input("Enter a number: ")) -... break -... except ValueError: -... print "Invalid number, try again..." -... ->>> # To raise exceptions -... raise ValueError, "your error message" -Traceback (most recent call last): - File "", line 2, in ? -ValueError: your error message -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes: the big picture} - \begin{itemize} - \item Lets you create new data types - \item Class is a template for an object belonging to that class - \item Note: in Python a class is also an object - \item Instantiating a class creates an instance (an object) - \item An instance encapsulates the state (data) and behavior - (methods) - \item Allows you to define an inheritance hierarchy - \begin{itemize} - \item ``A Honda car \alert{is a} car.'' - \item ``A car \alert{is an} automobile.'' - \item ``A Python \alert{is a} reptile.'' - \end{itemize} - \item Programmers need to think OO - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes: what's the big deal?} - \begin{itemize} - \item Lets you create objects that mimic a real problem being - simulated - \item Makes problem solving more natural and elegant - \item Easier to create code - \item Allows for code-reuse - \item Polymorphism - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Class definition and instantiation} - \begin{itemize} - \item Class definitions when executed create class objects - \item Instantiating the class object creates an instance of the - class - \end{itemize} -\footnotesize -\begin{lstlisting} -class Foo(object): - pass -# class object created. -# Create an instance of Foo. -f = Foo() -# Can assign an attribute to the instance -f.a = 100 -print f.a -100 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes \ldots} - \begin{itemize} - \item All attributes are accessed via the \typ{object.attribute} - syntax - \item Both class and instance attributes are supported - \item \emph{Methods} represent the behavior of an object: crudely - think of them as functions ``belonging'' to the object - \item All methods in Python are ``virtual'' - \item Inheritance through subclassing - \item Multiple inheritance is supported - \item No special public and private attributes: only good - conventions - \begin{itemize} - \item \verb+object.public()+: public - \item \verb+object._private()+ \& \verb+object.__priv()+: - non-public - \end{itemize} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes: examples} -\begin{lstlisting} -class MyClass(object): - """Example class (this is the class docstring).""" - i = 12345 # A class attribute - def f(self): - """This is the method docstring""" - return 'hello world' - ->>> a = MyClass() # creates an instance ->>> a.f() -'hello world' ->>> # a.f() is equivalent to MyClass.f(a) -... # This also explains why f has a 'self' argument. -... MyClass.f(a) -'hello world' -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes (continued)} - \begin{itemize} - \item \typ{self} is \alert{conventionally} the first argument for a - method - \item In previous example, \typ{a.f} is a method object - \item When \typ{a.f} is called, it is passed the instance \typ{a} as - the first argument - \item If a method called \verb+__init__+ exists, it is called when - the object is created - \item If a method called \verb+__del__+ exists, it is called before - the object is garbage collected - \item Instance attributes are set by simply ``setting'' them in - \typ{self} - \item Other special methods (by convention) like \verb+__add__+ let - you define numeric types: - {\footnotesize \url{http://docs.python.org/ref/specialnames.html} - \\ \url{http://docs.python.org/ref/numeric-types.html} - } - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes: examples} -\begin{lstlisting} -class Bag(MyClass): # Shows how to derive classes - def __init__(self): # called on object creation. - self.data = [] # an instance attribute - def add(self, x): - self.data.append(x) - def addtwice(self, x): - self.add(x) - self.add(x) ->>> a = Bag() ->>> a.f() # Inherited method -'hello world' ->>> a.add(1); a.addtwice(2) ->>> a.data -[1, 2, 2] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Derived classes} - \begin{itemize} - \item Call the parent's \verb+__init__+ if needed - \item If you don't need a new constructor, no need to define it in subclass - \item Can also use the \verb+super+ built-in function - \end{itemize} -\begin{lstlisting} -class AnotherBag(Bag): - def __init__(self): - # Must call parent's __init__ explicitly - Bag.__init__(self) - # Alternatively use this: - super(AnotherBag, self).__init__() - # Now setup any more data. - self.more_data = [] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes: polymorphism} -\begin{lstlisting} -class Drawable(object): - def draw(self): - # Just a specification. - pass -\end{lstlisting} -\mode{\pause} -\begin{lstlisting} -class Square(Drawable): - def draw(self): - # draw a square. -class Circle(Drawable): - def draw(self): - # draw a circle. -\end{lstlisting} -\mode{\pause} -\begin{lstlisting} -class Artist(Drawable): - def draw(self): - for obj in self.drawables: - obj.draw() -\end{lstlisting} -\end{frame} - -\subsection{Miscellaneous} - -\begin{frame}[fragile] - \frametitle{Stand-alone scripts} -Consider a file \typ{f.py}: -\begin{lstlisting} -#!/usr/bin/env python -"""Module level documentation.""" -# First line tells the shell that it should use Python -# to interpret the code in the file. -def f(): - print "f" - -# Check if we are running standalone or as module. -# When imported, __name__ will not be '__main__' -if __name__ == '__main__': - # This is not executed when f.py is imported. - f() -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{List comprehensions} -\begin{lstlisting} ->>> veg = ['tomato', 'cabbage', 'carrot', 'potato'] ->>> [x.upper() for x in veg] -['TOMATO', 'CABBAGE', 'CARROT', 'POTATO'] ->>> vec = range(0, 8) ->>> even = [x for x in vec if x%2 == 0] ->>> even -[0, 2, 4, 6] ->>> [x*x for x in even] -[0, 4, 16, 36] ->>> odd = [x for x in vec if x%2 == 1] ->>> odd -[1, 3, 5, 7] ->>> [x*y for x in even for y in odd] -[0, 0, 0, 0, 2, 6, 10, 14, 4, 12, 20, 28, 6, 18,30,42] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More IPython features} - \begin{itemize} - \item Input and output caching: - \begin{itemize} - \item \verb+In+: a list of all entered input - \item \verb+Out+: a dict of all output - \item \verb+_+, \verb+__+, \verb+__+ are the last three results as - is \verb+_N+ - \item \verb+%hist [-n]+ macro shows previous history, \verb+-n+ - suppresses line number information - \end{itemize} - \item Log the session using \verb+%logstart+, \verb+%logon+ and - \verb+%logoff+ - \item \verb+%run [options] file[.py]+ -- running Python code - \begin{itemize} - \item \verb+%run -d [-b]+: debug script with pdb - \verb+N+ is the line number to break at (defaults to 1) - \item \verb+%run -t+: time the script - \item \verb+%run -p+: Profile the script - \end{itemize} - \item \verb+%prun+ runs a statement/expression under the profiler - \item \verb+%macro [options] macro_name n1-n2 n3-n4 n6+ save specified - lines to a macro with name \verb+macro_name+ - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More IPython features \ldots} - \begin{itemize} - \item \verb+%edit [options] [args]+: edit lines of code or file - specified in editor (configure editor via \verb+$EDITOR+) - \item \verb+%cd+ changes directory, see also \verb+%pushd, %popd, %dhist+ - \item Shell access - \begin{itemize} - \item \verb+!command+ runs a shell command and returns its output - \item \verb+files = %sx ls+ or \verb+files = !ls+ sets - \verb+files+ to all result of the \verb+ls+ command - \item \verb+%sx+ is quiet - \item \verb+!ls $files+ passes the \verb+files+ variable to the - shell command - \item \verb+%alias alias_name cmd+ creates an alias for a system - command - \end{itemize} - \item \verb+%colors+ lets you change the color scheme to - \verb+NoColor, Linux, LightBG+ - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More IPython features \ldots} - \begin{itemize} - \item Use \verb+;+ at the end of a statement to suppress printing - output - \item \verb+%bookmark+: store a bookmarked location, for use with \verb+%cd+ - \item \verb+%who, %whos+: print information on variables - \item \verb+%save [options] filename n1-n2 n3-n4+: save lines to a - file - \item \verb+%time statement+: Time execution of a Python statement or - expression - \item \verb+%timeit [-n -r [-t|-c]] statement+: time execution - using Python's timeit module - \item Can define and use profiles to setup IPython differently: - \verb+math, scipy, numeric, pysh+ etc. - \item \verb+%magic+: \alert{Show help on all magics} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{File handling} -\begin{lstlisting} ->>> # Reading files: -... f = open('/path/to/file_name') ->>> data = f.read() # Read entire file. ->>> line = f.readline() # Read one line. ->>> # Read entire file appending each line into a list -... lines = f.readlines() ->>> f.close() # close the file. ->>> # Writing files: -... f = open('/path/to/file_name', 'w') ->>> f.write('hello world\n') -\end{lstlisting} - \begin{itemize} - \item \typ{tell()}: returns int of current position - \item \typ{seek(pos)}: moves current position to specified byte - \item Call \typ{close()} when done using a file - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Math} - \begin{itemize} - \item \typ{math} module provides basic math routines for - floats - \item \typ{cmath} module provides math routies for complex - numbers - \item \typ{random}: provides pseudo-random number generators - for various distributions - \item These are always available and part of the standard library - \item More serious math is provided by the NumPy/SciPy modules -- - these are not standard and need to be installed separately - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Timing and profiling} - \begin{itemize} - \item Timing code: use the \typ{time} module - \item Read up on \typ{time.time()} and \typ{time.clock()} - \item \typ{timeit}: is a better way of doing timing - \item IPython has handy \typ{time} and \typ{timeit} macros (type - \typ{timeit?} for help) - \item IPython lets you debug and profile code via the \typ{run} - macro (type \typ{run?} on the prompt to learn more) - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Odds and ends} - \begin{itemize} - \item \typ{dir([object])} function: attributes of given object - \item \typ{type(object)}: returns type information - \item \typ{str(), repr()}: convert object to string representation - \item \typ{isinstance, issubclass} - \item \typ{assert} statements let you do debugging assertions in - code - \item \typ{csv} module: reading and writing CSV files - \item \typ{pickle}: lets you save and load Python objects - (\alert{serialization}) - \item \typ{sys.argv}: command line arguments - \item \typ{os.path}: common path manipulations - \item Check out the Python Library reference: - \url{http://docs.python.org/lib/lib.html} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Test driven development (TDD)} - \begin{itemize} - \item Why? - \begin{itemize} - - \item Forces you to write reusable code! - - \item Think about the API - - \item More robust - - \item Makes refactoring very easy - - \end{itemize} - \item How? Python offers three major ways of doing this - \begin{itemize} - \item doctest - \item unittest - \item nosetest (and similar like py.test) - \end{itemize} - - \item Test every piece of functionality you offer - - \item This isn't a formal introduction but more a practical one - - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Unit test} -\begin{lstlisting} -import unittest - -class MyTestCase(unittest.TestCase): - def setUp(self): - # Called *before* each test_* - def tearDown(self): - # Called *after* each test_* - def test_something(self): - "docstring" - # Test code. - self.assertEqual(x, y) - self.assertRaises(ValueError, func, arg1, arg2 ...) - -if __name__ == '__main__': - unittest.main() -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Nosetest} -\begin{lstlisting} -import particle -def test_particle(): - # Use asserts here. - p = particle.Particle(1.0) - assert p.property[0] == 1.0 - assert p.property[2] == 0.0 - -if __name__ == '__main__': - import nose - nose.main() -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Testing} - \begin{itemize} - \item More details: see library reference and search for nosetest - \end{itemize} -\end{frame} - -\section{Numerics \& Plotting} - -\subsection{NumPy Arrays} - -\newcommand{\num}{\texttt{numpy}} - -\begin{frame} - \frametitle{The \num\ module} - \begin{itemize} - \item Manipulating large Python lists for scientific computing is - \alert{slow} - \item Most complex computations can be reduced to a few standard - operations - \item The \num\ module provides: - \begin{itemize} - \item An efficient and powerful array type for various common data - types - \item Abstracts out the most commonly used standard operations on - arrays - \end{itemize} - \item Numeric was the first, then came \texttt{numarray}. - \texttt{numpy} is the latest and is the future - \item This course uses \num\ and only covers the absolute basics - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Basic concepts} - \begin{itemize} - \item \num\ arrays are of a fixed size (\typ{arr.size}) and have the - same type (\typ{arr.dtype}) - \item \num\ arrays may have arbitrary dimensionality - \item The \typ{shape} of an array is the extent (length) of the - array along each dimension - \item The \typ{rank(arr)} of an array is the ``dimensionality'' of the - array - \item The \typ{arr.itemsize} is the number of bytes (8-bits) used for - each element of the array - \item \alert{Note:} The \typ{shape} and \typ{rank} may change as - long as the \typ{size} of the array is fixed - \item \alert{Note:} \typ{len(arr) != arr.size} in general - \item \alert{Note:} By default array operations are performed - \alert{elementwise} - \item Indices start from 0 - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Examples of \num} -\begin{lstlisting} -# Simple array math example ->>> from numpy import * ->>> a = array([1,2,3,4]) ->>> b = array([2,3,4,5]) ->>> a + b # Element wise addition! -array([3, 5, 7, 9]) - ->>> print pi, e # Pi and e are defined. -3.14159265359 2.71828182846 -# Create array from 0 to 10 ->>> x = arange(0.0, 10.0, 0.05) ->>> x *= 2*pi/10 # multiply array by scalar value -array([ 0.,0.0314,...,6.252]) -# apply functions to array. ->>> y = sin(x) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More examples of \num} -\vspace*{-8pt} -\begin{lstlisting} -# Size, shape, rank, type etc. ->>> x = array([1., 2, 3, 4]) ->>> size(x) -4 ->>> x.dtype # or x.dtype.char -'d' ->>> x.shape -(4,) ->>> print rank(x), x.itemsize -1 8 ->>> x.tolist() -[1.0, 2.0, 3.0, 4.0] -# Array indexing ->>> x[0] = 10 ->>> print x[0], x[-1] -10.0 4.0 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Multi-dimensional arrays} -\begin{lstlisting} ->>> a = array([[ 0, 1, 2, 3], -... [10,11,12,13]]) ->>> a.shape # (rows, columns) -(2, 4) -# Accessing and setting values ->>> a[1,3] -13 ->>> a[1,3] = -1 ->>> a[1] # The second row -array([10,11,12,-1]) - -# Flatten/ravel arrays to 1D arrays ->>> a.flat # or ravel(a) -array([0,1,2,3,10,11,12,-1]) -# Note: flat references original memory -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Slicing arrays} -\begin{lstlisting} ->>> a = array([[1,2,3], [4,5,6], [7,8,9]]) ->>> a[0,1:3] -array([2, 3]) ->>> a[1:,1:] -array([[5, 6], - [8, 9]]) ->>> a[:,2] -array([3, 6, 9]) -# Striding... ->>> a[0::2,0::2] -array([[1, 3], - [7, 9]]) -# All these slices are references to the same memory! -\end{lstlisting} -\end{frame} - -% \begin{frame}[fragile] -% \frametitle{Array types and typecodes} -% \begin{tabular}[c]{|c|c|p{2.75in}|} -% \hline -% Character & Bits (bytes) & Type name \\ -% \hline -% D & 128 (16) & \typ{Complex, Complex64}\\ -% F & 64 (8) & \typ{Complex0, Complex8, Complex16} \\ -% d & 64 (8) & \typ{Float, Float64} \\ -% f & 32 (4) & \typ{Float0, Float8, Float16} \\ -% i & 32 (4) & \typ{Int32} \\ -% l & 32 (4) & \typ{Int} \\ -% O & 4 (1) & \typ{PyObject} \\ -% %b 8 (1) UnsignedInt8 -% %1 (one) 8 (1) Int8 -% %s 16 (2) Int16 -% \hline -% \end{tabular} -% \begin{lstlisting} -% # Examples -% >>> f = array([1,2,3], Float32) -% >>> c = array([1,2,3], Complex32) -% >>> print f, c -% [ 1. 2. 3.] [ 1.+0.j 2.+0.j 3.+0.j] -% \end{lstlisting} -% \end{frame} - -\begin{frame}[fragile] - \frametitle{Array creation functions} - \begin{itemize} - \item \typ{array(object, dtype=None, copy=1,order=None, subok=0,ndmin=0)} - \item \typ{arange(start, stop=None, step=1, dtype=None)} - \item \typ{linspace(start, stop, num=50, endpoint=True, retstep=False)} - \item \typ{ones(shape, dtype=None, order='C')} - \item \typ{zeros((d1,...,dn),dtype=float,order='C')} - \item \typ{identity(n)} - \item \typ{empty((d1,...,dn),dtype=float,order='C')} - \item \typ{ones\_like(x)}, \typ{zeros\_like(x)}, \typ{empty\_like(x)} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Array math} - \begin{itemize} - \item Basic \alert{elementwise} math (given two arrays \typ{a, b}): - \begin{itemize} - \item \typ{a + b $\rightarrow$ add(a, b)} - \item \typ{a - b, $\rightarrow$ subtract(a, b)} - \item \typ{a * b, $\rightarrow$ multiply(a, b)} - \item \typ{a / b, $\rightarrow$ divide(a, b)} - \item \typ{a \% b, $\rightarrow$ remainder(a, b)} - \item \typ{a ** b, $\rightarrow$ power(a, b)} - \end{itemize} - \item Inplace operators: \typ{a += b}, or \typ{add(a, b, - a)} etc. - \item Logical operations: \typ{equal (==)}, \typ{not\_equal (!=)}, - \typ{less (<)}, \typ{greater (>)} etc. - \item Trig and other functions: \typ{sin(x), arcsin(x), sinh(x), - exp(x), sqrt(x)} etc. - \item \typ{sum(x, axis=0), product(x, axis=0)}: sum and product of array elements - \item \typ{dot(a, b)} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Advanced} - \begin{itemize} - \item Only scratched the surface of \num - \item Ufunc methods: \typ{reduce, accumulate, outer, reduceat} - \item Typecasting - \item More functions: \typ{take, choose, where, compress, - concatenate} - \item Array broadcasting and \typ{None} - \end{itemize} -\end{frame} - -\subsection{Plotting: Matplotlib} - -\begin{frame} - \frametitle{About \texttt{matplotlib}} - \begin{itemize} - \item Easy to use, scriptable, ``Matlab-like'' 2D plotting - \item Publication quality figures and interactive capabilities - \item Plots, histograms, power spectra, bar charts, errorcharts, - scatterplots, etc. - \item Also does polar plots, maps, contours - \item Support for simple \TeX\ markup - \item Multiple output backends (images, EPS, SVG, wx, Agg, Tk, GTK) - \item Cross-platform: Linux, Win32, Mac OS X - \item Good idea to use via IPython: \typ{ipython -pylab} - \item From scripts use: \typ{import pylab} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{More information} - \begin{itemize} - \item More information here: \url{http://matplotlib.sf.net} - \item \url{http://matplotlib.sf.net/tutorial.html} - \item \url{http://matplotlib.sf.net/screenshots.html} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic plotting with \texttt{matplotlib}} -\begin{lstlisting} ->>> x = arange(0, 2*pi, 0.05) ->>> plot(x, sin(x)) # Same as plot(x, sin(x), 'b-') ->>> plot(x, sin(x), 'ro') ->>> axis([0,2*pi, -1,1]) ->>> xlabel(r'$\chi$', color='g') ->>> ylabel(r'sin($\chi$)', color='r') ->>> title('A simple figure', fontsize=20) ->>> savefig('/tmp/test.eps') -# Multiple plots in one figure ->>> t = arange(0.0, 5.2, 0.2) -# red dashes, blue squares and green triangles ->>> plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic plotting \ldots} -\begin{lstlisting} -# Set properties of objects: ->>> plot(x, sin(x), linewidth=2.0, color='r') ->>> l, = plot(x, sin(x)) ->>> setp(l, linewidth=2.0, color='r') ->>> l.set_linewidth(2.0); l.set_color('r') ->>> draw() # Redraws current figure. ->>> setp(l) # Prints available properties ->>> close() # Closes the figure. -# Multiple figures: ->>> figure(1); plot(x, sin(x)) ->>> figure(2); plot(x, tanh(x)) ->>> figure(1); title('Easy as 1,2,3') -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic plotting \ldots} -\begin{lstlisting} ->>> figure(1) ->>> subplot(211) # Same as subplot(2, 1, 1) ->>> plot(x, cos(5*x)*exp(-x)) ->>> subplot(2, 1, 2) ->>> plot(x, cos(5*x), 'r--', label='cosine') ->>> plot(x, sin(5*x), 'g--', label='sine') ->>> legend() # Or legend(['cosine', 'sine']) ->>> text(1,0, '(1,0)') ->>> axes = gca() # Current axis ->>> fig = gcf() # Current figure -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{X-Y plot} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/xyplot} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -t1 = arange(0.0, 5.0, 0.1) -t2 = arange(0.0, 5.0, 0.02) -t3 = arange(0.0, 2.0, 0.01) -subplot(211) -plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', - t2, cos(2*pi*t2)*exp(-t2), 'k') -grid(True) -title('A tale of 2 subplots') -ylabel('Damped') -subplot(212) -plot(t3, cos(2*pi*t3), 'r--') -grid(True) -xlabel('time (s)') -ylabel('Undamped') -\end{lstlisting} - \end{block} - \end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Errorbar} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/errorbar} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -t = arange(0.1, 4, 0.1) -s = exp(-t) -e = 0.1*abs(randn(len(s))) -f = 0.1*abs(randn(len(s))) -g = 2*e -h = 2*f -errorbar(t, s, [e,g], f, fmt='o') -xlabel('Distance (m)') -ylabel('Height (m)') -title('Mean and standard error '\ - 'as a function of distance') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Semi-log and log-log plots} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/log} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -dt = 0.01 -t = arange(dt, 20.0, dt) -subplot(311) -semilogy(t, exp(-t/5.0)) -ylabel('semilogy') -grid(True) -subplot(312) -semilogx(t, sin(2*pi*t)) -ylabel('semilogx') -grid(True) -# minor grid on too -gca().xaxis.grid(True, which='minor') -subplot(313) -loglog(t, 20*exp(-t/10.0), basex=4) -grid(True) -ylabel('loglog base 4 on x') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Histogram} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/histogram} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -mu, sigma = 100, 15 -x = mu + sigma*randn(10000) -# the histogram of the data -n, bins, patches = hist(x, 100, normed=1) -# add a 'best fit' line -y = normpdf( bins, mu, sigma) -l = plot(bins, y, 'r--', linewidth=2) -xlim(40, 160) -xlabel('Smarts') -ylabel('P') -title(r'$\rm{IQ:}\/ \mu=100,\/ \sigma=15$') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Bar charts} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/barchart} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -N = 5 -menMeans = (20, 35, 30, 35, 27) -menStd = ( 2, 3, 4, 1, 2) -# the x locations for the groups -ind = arange(N) -# the width of the bars -width = 0.35 -p1 = bar(ind, menMeans, width, - color='r', yerr=menStd) -womenMeans = (25, 32, 34, 20, 25) -womenStd = ( 3, 5, 2, 3, 3) -p2 = bar(ind+width, womenMeans, width, - color='y', yerr=womenStd) -ylabel('Scores') -title('Scores by group and gender') -xticks(ind+width, - ('G1', 'G2', 'G3', 'G4', 'G5')) -xlim(-width,len(ind)) -yticks(arange(0,41,10)) -legend((p1[0], p2[0]), - ('Men', 'Women'), shadow=True) -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Pie charts} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.4in} - \includegraphics[height=2.0in, interpolate=true]{data/piechart} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -# make a square figure and axes -figure(1, figsize=(8,8)) -ax = axes([0.1, 0.1, 0.8, 0.8]) -labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' -fracs = [15,30,45, 10] -explode=(0, 0.05, 0, 0) -pie(fracs, explode=explode, labels=labels, - autopct='%1.1f%%', shadow=True) -title('Raining Hogs and Dogs', - bbox={'facecolor':'0.8', 'pad':5}) -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Scatter plots} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.4in} - \includegraphics[height=2in, interpolate=true]{data/scatter} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -N = 30 -x = 0.9*rand(N) -y = 0.9*rand(N) -# 0 to 10 point radiuses -area = pi*(10 * rand(N))**2 -volume = 400 + rand(N)*450 -scatter(x,y,s=area, marker='o', c=volume, - alpha=0.75) -xlabel(r'$\Delta_i$', size='x-large') -ylabel(r'$\Delta_{i+1}$', size='x-large') -title(r'Volume and percent change') -grid(True) -colorbar() -savefig('scatter') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Polar} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/polar} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -figure(figsize=(8,8)) -ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, - axisbg='#d5de9c') -r = arange(0,1,0.001) -theta = 2*2*pi*r -polar(theta, r, color='#ee8d18', lw=3) -# the radius of the grid labels -setp(ax.thetagridlabels, y=1.075) -title(r"$\theta=4\pi r", fontsize=20) -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Contours} - \begin{columns} - \column{0.45\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/contour} - \column{0.525\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -x = arange(-3.0, 3.0, 0.025) -y = arange(-2.0, 2.0, 0.025) -X, Y = meshgrid(x, y) -Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -# difference of Gaussians -Z = 10.0 * (Z2 - Z1) -im = imshow(Z, interpolation='bilinear', - origin='lower', - cmap=cm.gray, extent=(-3,3,-2,2)) -levels = arange(-1.2, 1.6, 0.2) -# label every second level -clabel(CS, levels[1::2], inline=1, - fmt='%1.1f', fontsize=14) -CS = contour(Z, levels, - origin='lower', - linewidths=2, - extent=(-3,3,-2,2)) -# make a colorbar for the contour lines -CB = colorbar(CS, shrink=0.8, extend='both') -title('Lines with colorbar') -hot(); flag() -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Velocity vectors} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/quiver} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -X,Y = meshgrid(arange(0,2*pi,.2), - arange(0,2*pi,.2) ) -U = cos(X) -V = sin(Y) -Q = quiver(X[::3, ::3], Y[::3, ::3], - U[::3, ::3], V[::3, ::3], - color='r', units='x', - linewidths=(2,), - edgecolors=('k'), - headaxislength=5 ) -qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', - fontproperties= - {'weight': 'bold'}) -axis([-1, 7, -1, 7]) -title('triangular head; scale '\ - 'with x view; black edges') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Maps} - \includegraphics[height=2.5in, interpolate=true]{data/plotmap} - \begin{center} - \tiny - For details see \url{http://matplotlib.sourceforge.net/screenshots/plotmap.py} - \end{center} -\end{frame} - - -\subsection{SciPy} - -\begin{frame} - \frametitle{Using \texttt{SciPy}} - \begin{itemize} - \item SciPy is Open Source software for mathematics, science, and - engineering - \item \typ{import scipy} - \item Built on NumPy - \item Provides modules for statistics, optimization, integration, - linear algebra, Fourier transforms, signal and image processing, - genetic algorithms, ODE solvers, special functions, and more - \item Used widely by scientists world over - \item Details are beyond the scope of this tutorial - \end{itemize} -\end{frame} - -\section{Standard library} - -\subsection{Quick Tour} - -\begin{frame} - \frametitle{Standard library} - \begin{itemize} - \item Very powerful - \item ``Batteries included'' - \item Example standard modules taken from the tutorial - \begin{itemize} - \item Operating system interface: \typ{os} - \item System, Command line arguments: \typ{sys} - \item Regular expressions: \typ{re} - \item Math: \typ{math}, \typ{random} - \item Internet access: \typ{urllib2}, \typ{smtplib} - \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, - \typ{zipfile}, and \typ{tarfile} - \item Unit testing: \typ{doctest} and \typ{unittest} - \item And a whole lot more! - \end{itemize} - \item Check out the Python Library reference: - \url{http://docs.python.org/lib/lib.html} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Stdlib: examples} -\begin{lstlisting} ->>> import os ->>> os.system('date') -Fri Jun 10 22:13:09 IST 2005 -0 ->>> os.getcwd() -'/home/prabhu' ->>> os.chdir('/tmp') ->>> import os ->>> dir(os) - ->>> help(os) - -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Stdlib: examples} -\begin{lstlisting} ->>> import sys ->>> # Print the list of command line args to Python -... print sys.argv -[''] ->>> import re # Regular expressions ->>> re.findall(r'\bf[a-z]*', -... 'which foot or hand fell fastest') -['foot', 'fell', 'fastest'] ->>> re.sub(r'(\b[a-z]+) \1', r'\1', -... 'cat in the the hat') -'cat in the hat' -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Stdlib: examples} -\begin{lstlisting} ->>> import math ->>> math.cos(math.pi / 4.0) -0.70710678118654757 ->>> math.log(1024, 2) -10.0 ->>> import random ->>> random.choice(['apple', 'pear', 'banana']) -'pear' -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Stdlib: examples} -\begin{lstlisting} ->>> import urllib2 ->>> f = urllib2.urlopen('http://www.python.org/') ->>> print f.read(100) - ->> import zlib ->>> s = 'witch which has which witches wrist watch' ->>> len(s) -41 ->>> t = zlib.compress(s) ->>> len(t) -37 ->>> zlib.decompress(t) -'witch which has which witches wrist watch' ->>> zlib.crc32(t) --1438085031 -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Summary} - \begin{itemize} - \item Introduced Python - \item Basic syntax - \item Basic types and data structures - \item Control flow - \item Functions - \item Modules - \item Exceptions - \item Classes - \item Standard library - \end{itemize} -\end{frame} - -\end{document} - -\subsection{Basic data structures} -\begin{frame}{Lists} - \begin{itemize} - \item \texttt{species = [ 'humans', 'orcs', 'elves', 'dwarves' ]} - \item \texttt{ ids = [ 107, 109, 124, 141, 142, 144 ]} - \item \texttt{ oneliners = [ 'I will be back', 'Do or do not! No try!!', 42 ] } - \end{itemize} - - \begin{block}{List operations} - ids + [ 100, 102 ]\\ - species.append( 'unicorns')\\ - print oneliners[ 1 ]\\ - look up \alert{docs.python.org/tutorial/datastructures.html} - \end{block} -\end{frame} -\end{document} -\section{Python Tutorial} -\subsection{Preliminaries} -\begin{frame} - \frametitle{Using the interpreter} - \begin{itemize} - \item Starting up: \typ{python} or \typ{ipython} - \item Quitting: \typ{Control-D} or \typ{Control-Z} (on Win32) - \item Can use it like a calculator - \item Can execute one-liners via the \typ{-c} option: - \typ{python -c "print 'hello world'"} - \item Other options via \typ{python -h} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{IPython} - \begin{itemize} - \item Recommended interpreter, IPython: - \url{http://ipython.scipy.org} - \item Better than the default Python shell - \item Supports tab completion by default - \item Easier object introspection - \item Shell access! - \item Command system to allow extending its own behavior - \item Supports history (across sessions) and logging - \item Can be embedded in your own Python code - \item Support for macros - \item A flexible framework for your own custom interpreter - \item Other miscellaneous conveniences - \item We'll get back to this later - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic IPython features} - \begin{itemize} - \item Startup: \verb+ipython [options] files+ - \begin{itemize} - \item \verb+ipython [-wthread|-gthread|-qthread]+: - Threading modes to support wxPython, pyGTK and Qt - \item \verb+ipython -pylab+: Support for matplotlib - \end{itemize} - \item TAB completion: - \begin{itemize} - \item Type \verb+object_name.+ to see list of options - \item Also completes on file and directory names - \end{itemize} - \item \verb+object?+ shows docstring/help for any Python object - \item \verb+object??+ presents more docs (and source if possible) - \item Debugging with \verb+%pdb+ magic: pops up pdb on errors - \item Access history (saved over earlier sessions also) - \begin{itemize} - \item Use \texttt{}: move up history - \item Use \texttt{ string}: search history backwards - \item Use \texttt{Esc >}: get back to end of history - \end{itemize} - \item \verb+%run [options] file[.py]+ lets you run Python code - \end{itemize} -\end{frame} -% LocalWords: BDFL Guido Rossum PSF Nokia OO Zope CMS RedHat SciPy MayaVi spam -% LocalWords: IPython ipython stdin TypeError dict int elif PYTHONPATH IOError -% LocalWords: namespace Namespaces SyntaxError ZeroDivisionError NameError str -% LocalWords: ValueError subclassed def - - - \item Types are of two kinds: \alert{mutable} and \alert{immutable} - \item Immutable types: numbers, strings, \typ{None} and tuples - \item Immutables cannot be changed ``in-place'' - \item Mutable types: lists, dictionaries, instances, etc. - \item Mutable objects can be ``changed'' - \end{itemize} - - -\begin{frame} - \frametitle{Important!} - \begin{itemize} - \item Assignment to an object is by reference - \item Essentially, \alert{names are bound to objects} - \end{itemize} -\end{frame} - - -\end{document} -\begin{frame}[fragile] - \frametitle{Dictionaries} - \begin{itemize} - \item Associative arrays/mappings - \item Indexed by ``keys'' (keys must be immutable) - \item \typ{dict[key] = value} - \item \typ{keys()} returns all keys of the dict - \item \typ{values()} returns the values of the dict - \item \verb+has_key(key)+ returns if \typ{key} is in the dict - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Dictionaries: example} - \begin{lstlisting} ->>> tel = {'jack': 4098, 'sape': 4139} ->>> tel['guido'] = 4127 ->>> tel -{'sape': 4139, 'guido': 4127, 'jack': 4098} ->>> tel['jack'] -4098 ->>> del tel['sape'] ->>> tel['irv'] = 4127 ->>> tel -{'guido': 4127, 'irv': 4127, 'jack': 4098} ->>> tel.keys() -['guido', 'irv', 'jack'] ->>> tel.has_key('guido') -True - \end{lstlisting} -\end{frame} - -\subsection{Control flow, functions} - - - -\begin{frame}[fragile] - \frametitle{\typ{If} example} - \begin{lstlisting} ->>> a = ['cat', 'window', 'defenestrate'] ->>> if 'cat' in a: -... print "meaw" -... -meaw ->>> pets = {'cat': 1, 'dog':2, 'croc': 10} ->>> if 'croc' in pets: -... print pets['croc'] -... -10 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{for} example} - \begin{lstlisting} ->>> a = ['cat', 'window', 'defenestrate'] ->>> for x in a: -... print x, len(x) -... -cat 3 -window 6 -defenestrate 12 ->>> knights = {'gallahad': 'the pure', -... 'robin': 'the brave'} ->>> for k, v in knights.iteritems(): -... print k, v -... -gallahad the pure -robin the brave -\end{lstlisting} -\end{frame} diff -r ae070c133120 -r 24992ab48f2b day1/Problems.tex --- a/day1/Problems.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,594 +0,0 @@ -\documentclass[12pt]{article} -\title{Python Workshop\\Problems and Exercises} -\author{Asokan Pichai\\Prabhu Ramachandran} -\begin{document} -\maketitle - -\section{Python} -\subsection{Getting started} - \begin{verbatim} ->>> print 'Hello Python' ->>> print 3124 * 126789 ->>> 1786 % 12 ->>> 3124 * 126789 ->>> a = 3124 * 126789 ->>> big = 12345678901234567890 ** 3 ->>> verybig = big * big * big * big ->>> 12345**6, 12345**67, 12345**678 - ->>> s = 'Hello ' ->>> p = 'World' ->>> s + p ->>> s * 12 ->>> s * s ->>> s + p * 12, (s + p)* 12 ->>> s * 12 + p * 12 ->>> 12 * s -\end{verbatim} -\newpage - -\begin{verbatim} ->>> 17/2 ->>> 17/2.0 ->>> 17.0/2 ->>> 17.0/8.5 ->>> int(17/2.0) ->>> float(17/2) ->>> str(17/2.0) ->>> round( 7.5 ) -\end{verbatim} - -\subsection{Mini exercises} -\begin{itemize} - \item Round a float to the nearest integer, using \texttt{int()}? - \item What does this do? \\\texttt{round(amount * 10) /10.0 } - \item How to round a number to the nearest 5 paise? - \begin{description} - \item[Remember] 17.23 $\rightarrow$ 17.25,\\ while 17.22 $\rightarrow$ 17.20 - \end{description} - \item How to round a number to the nearest 20 paise? -\end{itemize} - -\begin{verbatim} - amount = 12.68 - denom = 0.05 - nCoins = round(amount/denom) - rAmount = nCoins * denom -\end{verbatim} - -\subsection{Dynamic typing} -\begin{verbatim} -a = 1 -a = 1.1 -a = "Now I am a string!" -\end{verbatim} - -\subsection{Comments} -\begin{verbatim} -a = 1 # In-line comments -# Comment in a line to itself. -a = "# This is not a comment!" - \end{verbatim} - -\section{Data types} -\subsection{Numbers} - \begin{verbatim} ->>> a = 1 # Int. ->>> l = 1000000L # Long ->>> e = 1.01325e5 # float ->>> f = 3.14159 # float ->>> c = 1+1j # Complex! ->>> print f*c/a -(3.14159+3.14159j) ->>> print c.real, c.imag -1.0 1.0 ->>> abs(c) -1.4142135623730951 ->>> abs( 8 - 9.5 ) -1.5 - \end{verbatim} - -\subsection{Boolean} - \begin{verbatim} ->>> t = True ->>> f = not t -False ->>> f or t -True ->>> f and t -False ->>> NOT True -\ldots ??? ->>> not TRUE -\ldots ??? -\end{verbatim} - -\subsection{Relational and logical operators} - \begin{verbatim} ->>> a, b, c = -1, 0, 1 ->>> a == b -False ->>> a <= b -True ->>> a + b != c -True ->>> a < b < c -True ->>> c >= a + b -True - \end{verbatim} - -\subsection{Strings} - \begin{verbatim} -s = 'this is a string' -s = 'This one has "quotes" inside!' -s = "I have 'single-quotes' inside!" -l = "A string spanning many lines\ -one more line\ -yet another" -t = """A triple quoted string does -not need to be escaped at the end and -"can have nested quotes" etc.""" - \end{verbatim} - - \begin{verbatim} ->>> w = "hello" ->>> print w[0] + w[2] + w[-1] -hlo ->>> len(w) # guess what -5 ->>> s = u'Unicode strings!' ->>> # Raw strings (note the leading 'r') -... r_s = r'A string $\alpha \nu$' - \end{verbatim} - \begin{verbatim} ->>> w[0] = 'H' # Can't do that! -Traceback (most recent call last): - File "", line 1, in ? -TypeError: object does not support item assignment - \end{verbatim} - - \subsection{IPython} - \begin{verbatim} -In [1]: a = 'hello world' -In [2]: a.startswith('hell') -Out[2]: True -In [3]: a.endswith('ld') -Out[3]: True -In [4]: a.upper() -Out[4]: 'HELLO WORLD' -In [5]: a.upper().lower() -Out[5]: 'hello world' - -In [6]: a.split() -Out[6]: ['hello', 'world'] -In [7]: ''.join(['a', 'b', 'c']) -Out[7]: 'abc' -In [8] 'd' in ''.join( 'a', 'b', 'c') -Out[8]: False -a.split( 'o' )} -??? -'x'.join( a.split( 'o' ) ) -??? - -In [11]: x, y = 1, 1.2 -In [12]: 'x is %s, y is %s' %(x, y) -Out[12]: 'x is 1, y is 1.234' - -'x is \%d, y is \%f' \%(x, y) -??? -'x is \%3d, y is \%4.2f' \%(x, y) -??? - \end{verbatim} - -\subsection{A classic problem} - How to interchange values of two variables? Please note that the type of either variable is unknown and it is not necessary that both be of the same type even! - -\subsection{Basic conditional flow} - \begin{verbatim} -In [21]: a = 7 -In [22]: b = 8 -In [23]: if a > b: - ....: print 'Hello' - ....: else: - ....: print 'World' - ....: - ....: -World - \end{verbatim} - -\subsection{\texttt{If...elif...else} example} -\begin{verbatim} -x = int(raw_input("Enter an integer:")) -if x < 0: - print 'Be positive!' -elif x == 0: - print 'Zero' -elif x == 1: - print 'Single' -else: - print 'More' -\end{verbatim} - -\subsection{Basic looping} - \begin{verbatim} -# Fibonacci series: -# the sum of two elements -# defines the next -a, b = 0, 1 -while b < 10: - print b, - a, b = b, a + b - -\end{verbatim} - -\section{Problem set 1} -All the problems can be solved using \texttt{if} and \texttt{while} -\begin{description} - \item[1.1] Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ -These are called $Armstrong$ numbers. - -\item[1.2 Collatz sequence] -\begin{enumerate} - \item Start with an arbitrary (positive) integer. - \item If the number is even, divide by 2; if the number is odd multiply by 3 and add 1. - \item Repeat the procedure with the new number. - \item There is a cycle of 4, 2, 1 at which the procedure loops. -\end{enumerate} - Write a program that accepts the starting value and prints out the Collatz sequence. - - \item[1.3 Kaprekar's constant] - \begin{enumerate} - \item Take a four digit number--with at least two digits different. - \item Arrange the digits in ascending and descending order, giving A and D respectively. - \item Leave leading zeros in A! - \item Subtract A from D. - \item With the result, repeat from step 2. - \end{enumerate} - Write a program to accept a 4-digit number and display the progression to Kaprekar's constant. - -\item[1.4] - Write a program that prints the following pyramid on the screen. - \begin{verbatim} -1 -2 2 -3 3 3 -4 4 4 4 - \end{verbatim} -The number of lines must be obtained from the user as input.\\ -When can your code fail? -\end{description} - -\subsection{Functions: examples} - \begin{verbatim} -def signum( r ): - """returns 0 if r is zero - -1 if r is negative - +1 if r is positive""" - if r < 0: - return -1 - elif r > 0: - return 1 - else: - return 0 - -def pad( n, size ): - """pads integer n with spaces - into a string of length size - """ - SPACE = ' ' - s = str( n ) - padSize = size - len( s ) - return padSize * SPACE + s - \end{verbatim} -What about \%3d? - -\subsection {What does this function do?} - \begin{verbatim} -def what( n ): - if n < 0: n = -n - while n > 0: - if n % 2 == 1: - return False - n /= 10 - return True - \end{verbatim} -\newpage - -\subsection{What does this function do?} -\begin{verbatim} -def what( n ): - i = 1 - while i * i < n: - i += 1 - return i * i == n, i - \end{verbatim} - -\subsection{What does this function do?} - \begin{verbatim} -def what( n, x ): - z = 1.0 - if n < 0: - x = 1.0 / x - n = -n - while n > 0: - if n % 2 == 1: - z *= x - n /= 2 - x *= x - return z - \end{verbatim} - -\section{Problem set 2} - The focus is on writing functions and calling them. -\begin{description} - \item[2.1] Write a function to return the gcd of two numbers. - \item[2.2 Primitive Pythagorean Triads] A pythagorean triad $(a,b,c)$ has the property $a^2 + b^2 = c^2$.\\By primitive we mean triads that do not `depend' on others. For example, (4,3,5) is a variant of (3,4,5) and hence is not primitive. And (10,24,26) is easily derived from (5,12,13) and should not be displayed by our program. \\ -Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100 -\item[2.3] Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\\For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square). -\item[2.4 Aliquot] The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. For example, the aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.\\ - Write a function that returns the aliquot number of a given number. -\item[2.5 Amicable pairs] A pair of numbers (a, b) is said to be \emph{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ - Example: \texttt{220, 284}\\ - Write a program that prints all five digit amicable pairs. -\end{description} - -\section{Lists} -\subsection{List creation and indexing} -\begin{verbatim} ->>> a = [] # An empty list. ->>> a = [1, 2, 3, 4] # More useful. ->>> len(a) -4 ->>> a[0] + a[1] + a[2] + a[-1] -10 -\end{verbatim} - -\begin{verbatim} ->>> a[1:3] # A slice. -[2, 3] ->>> a[1:-1] -[2, 3, 4] ->>> a[1:] == a[1:-1] -False -\end{verbatim} -Explain last result - -\newpage -\subsection{List: more slices} -\begin{verbatim} ->>> a[0:-1:2] # Notice the step! -[1, 3] ->>> a[::2] -[1, 3] ->>> a[-1::-1] -\end{verbatim} -What do you think the last one will do?\\ -\emph{Note: Strings also use same indexing and slicing.} - \subsection{List: examples} -\begin{verbatim} ->>> a = [1, 2, 3, 4] ->>> a[:2] -[1, 3] ->>> a[0:-1:2] -[1, 3] -\end{verbatim} -\emph{Lists are mutable (unlike strings)} - -\begin{verbatim} ->>> a[1] = 20 ->>> a -[1, 20, 3, 4] -\end{verbatim} - - \subsection{Lists are mutable and heterogenous} -\begin{verbatim} ->>> a = ['spam', 'eggs', 100, 1234] ->>> a[2] = a[2] + 23 ->>> a -['spam', 'eggs', 123, 1234] ->>> a[0:2] = [1, 12] # Replace items ->>> a -[1, 12, 123, 1234] ->>> a[0:2] = [] # Remove items ->>> a.append( 12345 ) ->>> a -[123, 1234, 12345] -\end{verbatim} - - \subsection{List methods} -\begin{verbatim} ->>> a = ['spam', 'eggs', 1, 12] ->>> a.reverse() # in situ ->>> a -[12, 1, 'eggs', 'spam'] ->>> a.append(['x', 1]) ->>> a -[12, 1, 'eggs', 'spam', ['x', 1]] ->>> a.extend([1,2]) # Extend the list. ->>> a.remove( 'spam' ) ->>> a -[12, 1, 'eggs', ['x', 1], 1, 2] -\end{verbatim} - - \subsection{List containership} - \begin{verbatim} ->>> a = ['cat', 'dog', 'rat', 'croc'] ->>> 'dog' in a -True ->>> 'snake' in a -False ->>> 'snake' not in a -True ->>> 'ell' in 'hello world' -True - \end{verbatim} - \subsection{Tuples: immutable} -\begin{verbatim} ->>> t = (0, 1, 2) ->>> print t[0], t[1], t[2], t[-1] -0 1 2 2 ->>> t[0] = 1 -Traceback (most recent call last): - File "", line 1, in ? -TypeError: object does not support item assignment -\end{verbatim} - Multiple return values are actually a tuple.\\ - Exchange is tuple (un)packing - \subsection{\texttt{range()} function} - \begin{verbatim} ->>> range(7) -[0, 1, 2, 3, 4, 5, 6] ->>> range( 3, 9) -[3, 4, 5, 6, 7, 8] ->>> range( 4, 17, 3) -[4, 7, 10, 13, 16] ->>> range( 5, 1, -1) -[5, 4, 3, 2] ->>> range( 8, 12, -1) -[] - \end{verbatim} - - \subsection{\texttt{for\ldots range(\ldots)} idiom} - \begin{verbatim} -In [83]: for i in range(5): - ....: print i, i * i - ....: - ....: -0 0 -1 1 -2 4 -3 9 -4 16 -\end{verbatim} - - \subsection{\texttt{for}: the list companion} - - \begin{verbatim} -In [84]: a = ['a', 'b', 'c'] -In [85]: for x in a: - ....: print x, chr( ord(x) + 10 ) - ....: -a k -b l -c m - \end{verbatim} - - \subsection{\texttt{for}: the list companion} - \begin{verbatim} -In [89]: for p, ch in enumerate( a ): - ....: print p, ch - ....: - ....: -0 a -1 b -2 c - \end{verbatim} -Try: \texttt{print enumerate(a)} - -\section{Problem set 3} - As you can guess, idea is to use \texttt{for}! - -\begin{description} - \item[3.1] Which of the earlier problems is simpler when we use \texttt{for} instead of \texttt{while}? - \item[3.2] Given an empty chessboard and one Bishop placed in any square, say (r, c), generate the list of all squares the Bishop could move to. - \item[3.3] Given two real numbers \texttt{a, b}, and an integer \texttt{N}, write a - function named \texttt{linspace( a, b, N)} that returns an ordered list - of \texttt{N} points starting with \texttt{a} and ending in \texttt{b} and - equally spaced.\\ - For example, \texttt{linspace(0, 5, 11)}, should return, \\ -\begin{verbatim} -[ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, - 3.0 , 3.5, 4.0 , 4.5, 5.0 ] -\end{verbatim} - \item[3.4a] Use the \texttt{linspace} function and generate a list of N tuples of the form\\ -\texttt{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions, -\begin{itemize} - \item \texttt{f(x) = sin(x)} - \item \texttt{f(x) = sin(x) + sin(10*x)}. -\end{itemize} - -\item[3.4b] Using the tuples generated earlier, determine the intervals where the roots of the functions lie. -\end{description} - -\section{IO} - \subsection{Simple tokenizing and parsing} - \begin{verbatim} -s = """The quick brown fox jumped - over the lazy dog""" -for word in s.split(): - print word.capitalize() - \end{verbatim} - - \begin{description} - \item[4.1] Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \texttt{[1,3,4,5,6,7,12,15,18,19,20,21]} -\end{description} - - \subsection{File handling} -\begin{verbatim} ->>> f = open('/path/to/file_name') ->>> data = f.read() # Read entire file. ->>> line = f.readline() # Read one line. ->>> f.close() # close the file. -\end{verbatim} -Writing files -\begin{verbatim} ->>> f = open('/path/to/file_name', 'w') ->>> f.write('hello world\n') ->>> f.close() -\end{verbatim} - - \subsection{File and \texttt{for}} -\begin{verbatim} ->>> f = open('/path/to/file_name') ->>> for line in f: -... print line -... -\end{verbatim} - - \begin{description} - \item[4.2] The given file has lakhs of records in the form: - \texttt{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}. - Some entries may be empty. Read the data from this file and print the - name of the student with the maximum total marks. - \item[4.3] For the same data file compute the average marks in different - subjects, the student with the maximum mark in each subject and also - the standard deviation of the marks. Do this efficiently. -\end{description} - -\section{Modules} -\begin{verbatim} ->>> sqrt(2) -Traceback (most recent call last): - File "", line 1, in -NameError: name 'sqrt' is not defined ->>> import math ->>> math.sqrt(2) -1.4142135623730951 - ->>> from math import sqrt ->>> from math import * ->>> from os.path import exists -\end{verbatim} - - \subsection{Modules: example} - \begin{verbatim} -# --- arith.py --- -def gcd(a, b): - if a%b == 0: return b - return gcd(b, a%b) -def lcm(a, b): - return a*b/gcd(a, b) -# ------------------ ->>> import arith ->>> arith.gcd(26, 65) -13 ->>> arith.lcm(26, 65) -130 - \end{verbatim} - - \begin{description} - \item[5.1] Put all the functions you have written so far as part of the problems - into one module called \texttt{iitb.py} and use this module from IPython. -\end{description} -\end{document} diff -r ae070c133120 -r 24992ab48f2b day1/Session-1.tex --- a/day1/Session-1.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,649 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -%\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\texttt{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -%%% This is from Fernando's setup. -% \usepackage{color} -% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} -% % Use and configure listings package for nicely formatted code -% \usepackage{listings} -% \lstset{ -% language=Python, -% basicstyle=\small\ttfamily, -% commentstyle=\ttfamily\color{blue}, -% stringstyle=\ttfamily\color{orange}, -% showstringspaces=false, -% breaklines=true, -% postbreak = \space\dots -% } - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Python:\\A great programming toolkit} - -\author[FOSSEE Team] {Asokan Pichai\\Prabhu Ramachandran} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {10, October 2009\\Day 1, Session 1} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} -%\logo{\pgfuseimage{iitmlogo}} - - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each subsection: -\AtBeginSubsection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - - -% If you wish to uncover everything in a step-wise fashion, uncomment -% the following command: -%\beamerdefaultoverlayspecification{<+->} - -%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \titlepage -\end{frame} -\begin{frame} - {Acknowledgements} - \begin{center} - This program is conducted by\\ - IIT, Bombay\\ - as part of the open source initiatives\\ - under the aegis of\\ - \alert{National Mission on Education through ICT,} \\ - Ministry of HRD. - \end{center} -\end{frame} - -\begin{frame} - \frametitle{Outline} - \tableofcontents - % You might wish to add the option [pausesections] -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TODO -% -% * Add slide on Python packages (modules) -% * Add slides on reference counting. - -\section{Agenda} -\begin{frame}{About the Workshop, Day 1} - \begin{description} - \item[Day 1, Session 1] Sat 09:30--11:00 - \item[Day 1, Session 2] Sat 11:15--12:45 - \item[Day 1, Session 3] Sat 13:45--15:15 - \item[Day 1, Session 4] Sat 15:30--17:00 - \end{description} -\end{frame} -\begin{frame}{About the Workshop, Day 2} - \begin{description} - \item[Day 2, Quiz] Sun 09:00--09:30 - \item[Day 2, Session 1] Sun 09:30--11:00 - \item[Day 2, Session 2] Sun 11:15--12:45 - \item[Day 2, Session 3] Sun 13:45--15:15 - \item[Day 2, Session 4] Sun 15:30--17:00 - \end{description} -\end{frame} - -\begin{frame}{About the Workshop} - \begin{block}{Intended Audience} - \begin{itemize} - \item Engg., Mathematics and Science teachers. - \item Interested students from similar streams. - \end{itemize} - \end{block} - - \begin{block}{Goal:} - Successful participants will be able to - \begin{itemize} - \item use Python as their scripting and problem solving language. - \item train the students to use Python for the same - \end{itemize} - \end{block} -\end{frame} - -\begin{frame}{Checklist} - \begin{block}{python} - Type python at the command line. Do you see version 2.5 or later? - \end{block} - \begin{block}{IPython} - Type ipython at the command line. Is it available? - \end{block} - \begin{block}{Editor} - We recommend scite. - \end{block} -\end{frame} - -\section{Overview} -\begin{frame} - \frametitle{Introduction} - \begin{itemize} - \item Creator and BDFL: Guido van Rossum - \item December 1989 - \item ``Python'' as in \emph {Monty Python's Flying Circus} - \item 2.6.x - \item PSF license (like BSD: no strings attached) - \item Highly cross platform - \item Nokia series 60! - \item \alert{Philosophy:} Simple and complete by design - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Resources} - \begin{itemize} - \item Part of many GNU/Linux distributions - \item Web: \url{http://www.python.org} - \item Doc: \url{http://www.python.org/doc} - \item Free Tutorials: - \begin{itemize} - \item Official Python tutorial: \url{http://docs.python.org/tut/tut.html} - \item Byte of Python: \url{http://www.byteofpython.info/} - \item Dive into Python: \url{http://diveintopython.org/} - \end{itemize} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Why Python?} - \begin{itemize} - \item Readable and easy to use - \item High level, interpreted, modular, OO - \item Much faster development cycle - \item Powerful interactive environment - \item Rapid application development - \item Rich standard library and modules - \item Interfaces well with C++, C and FORTRAN - \item \alert{More than a math package $\Rightarrow$ some extra work compared to math packages} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Use cases} - \begin{itemize} - \item NASA: Space Shuttle Mission Design - \item AstraZeneca: Collaborative Drug Discovery - \item ForecastWatch.com: Helps Meteorologists - \item Industrial Light \& Magic: Runs on Python - \item Zope: Commercial grade Toolkit - \item Plone: Professional high feature CMS - \item RedHat: install scripts, sys-admin tools - \item Django: A great web application framework - \item Google: A strong python shop - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{To sum up, python is\ldots} - \begin{itemize} - \item dynamically typed, interpreted $\rightarrow$ rapid testing/prototyping - \item powerful, very high level - \item has full introspection - \item Did we mention powerful? - \end{itemize} - \begin{block}{But \ldots} - may be wanting in performance. specialised resources such as SWIG, \alert{Cython} are available - \end{block} - \inctime{15} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 10 m, running 10m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{Python} - -\subsection{Getting Started} - -\begin{frame}[fragile] - \frametitle{At the prompt, type the following} - \begin{lstlisting} ->>> print 'Hello Python' ->>> print 3124 * 126789 ->>> 1786 % 12 ->>> 3124 * 126789 ->>> a = 3124 * 126789 ->>> big = 12345678901234567890 ** 3 ->>> verybig = big * big * big * big ->>> 12345**6, 12345**67, 12345**678 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{At the prompt, type the following} - \begin{lstlisting} ->>> s = 'Hello ' ->>> p = 'World' ->>> s + p ->>> s * 12 ->>> s * s ->>> s + p * 12, (s + p)* 12 ->>> s * 12 + p * 12 ->>> 12 * s - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{At the prompt, type the following} - \begin{lstlisting} ->>> 17/2 ->>> 17/2.0 ->>> 17.0/2 ->>> 17.0/8.5 ->>> int(17/2.0) ->>> float(17/2) ->>> str(17/2.0) ->>> round( 7.5 ) - \end{lstlisting} - \begin{block}{Mini exercise} - Round a float to the nearest integer, using \texttt{int()}? - \end{block} -\end{frame} - -\begin{frame}\frametitle{Midi exercises} - \begin{center} - \begin{itemize} - \item What does this do? - \item \texttt{round(amount * 10) /10.0 } - \end{itemize} - \end{center} -\end{frame} - -\begin{frame}\frametitle{More exercises} - \begin{center} - \begin{block}{Round sums} - How to round a number to the nearest 5 paise?\\ - \begin{description} - \item[Remember] 17.23 $\rightarrow$ 17.25,\\ while 17.22 $\rightarrow$ 17.20\\ - \end{description} - How to round a number to the nearest 20 paise? - \end{block} - \end{center} -\end{frame} - -\begin{frame}[fragile] \frametitle{A question of good style} - \begin{lstlisting} - amount = 12.68 - denom = 0.05 - nCoins = round(amount/denom) - rAmount = nCoins * denom - \end{lstlisting} - \pause - \begin{block}{Style Rule \#1} - Naming is 80\% of programming - \end{block} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Odds and ends} - \begin{itemize} - \item Case sensitive - \item Dynamically typed $\Rightarrow$ need not specify a type - \begin{lstlisting} -a = 1 -a = 1.1 -a = "Now I am a string!" - \end{lstlisting} - \item Comments: - \begin{lstlisting} -a = 1 # In-line comments -# Comment in a line to itself. -a = "# This is not a comment!" - \end{lstlisting} - \end{itemize} - \inctime{15} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 10 m, running 20m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\subsection{Data types} -\begin{frame} - \frametitle{Basic types} - \begin{itemize} - \item Numbers: float, int, long, complex - \item Strings - \item Boolean - \end{itemize} - \begin{block}{Also to be discussed later} - tuples, lists, dictionaries, functions, objects\ldots - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Numbers} - \vspace*{-0.25in} - \begin{lstlisting} ->>> a = 1 # Int. ->>> l = 1000000L # Long ->>> e = 1.01325e5 # float ->>> f = 3.14159 # float ->>> c = 1+1j # Complex! ->>> print f*c/a -(3.14159+3.14159j) ->>> print c.real, c.imag -1.0 1.0 ->>> abs(c) -1.4142135623730951 ->>> abs( 8 - 9.5 ) -1.5 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Boolean} - \begin{lstlisting} ->>> t = True ->>> f = not t -False ->>> f or t -True ->>> f and t -False - \end{lstlisting} - \begin{block}{Try:} - NOT True\\ - not TRUE - \end{block} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 10 m, running 30m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\begin{frame}[fragile] - \frametitle{Relational and logical operators} - \begin{lstlisting} ->>> a, b, c = -1, 0, 1 ->>> a == b -False ->>> a <= b -True ->>> a + b != c -True ->>> a < b < c -True ->>> c >= a + b -True - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Strings} - \begin{lstlisting} -s = 'this is a string' -s = 'This one has "quotes" inside!' -s = "I have 'single-quotes' inside!" -l = "A string spanning many lines\ -one more line\ -yet another" -t = """A triple quoted string does -not need to be escaped at the end and -"can have nested quotes" etc.""" - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More Strings} - \vspace*{-0.2in} - \begin{lstlisting} ->>> w = "hello" ->>> print w[0] + w[2] + w[-1] -hlo ->>> len(w) # guess what -5 ->>> s = u'Unicode strings!' ->>> # Raw strings (note the leading 'r') -... r_s = r'A string $\alpha \nu$' - \end{lstlisting} -\pause - \begin{lstlisting} ->>> w[0] = 'H' # Can't do that! -Traceback (most recent call last): - File "", line 1, in ? -TypeError: object does not support item assignment - \end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Let us switch to IPython} - Why? - \begin{block} - {Better help (and a lot more)} - Tab completion\\ - ?\\ - .?\\ - object.function? - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More on strings} - \begin{lstlisting} -In [1]: a = 'hello world' -In [2]: a.startswith('hell') -Out[2]: True -In [3]: a.endswith('ld') -Out[3]: True -In [4]: a.upper() -Out[4]: 'HELLO WORLD' -In [5]: a.upper().lower() -Out[5]: 'hello world' - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile]\frametitle{Still with strings} - \begin{lstlisting} -In [6]: a.split() -Out[6]: ['hello', 'world'] -In [7]: ''.join(['a', 'b', 'c']) -Out[7]: 'abc' -In [8] 'd' in ''.join(['a', 'b', 'c']) -Out[8]: False - \end{lstlisting} - \begin{block}{Try:} - \texttt{a.split( 'o' )}\\ - \texttt{'x'.join( a.split( 'o' ) )} - \end{block} -\end{frame} - -\begin{frame}[fragile]\frametitle{String formatting} - \begin{lstlisting} -In [11]: x, y = 1, 1.234 -In [12]: 'x is %s, y is %s' %(x, y) -Out[12]: 'x is 1, y is 1.234' - \end{lstlisting} - \begin{block}{Try:} - \texttt{'x is \%d, y is \%f' \%(x, y) }\\ - \texttt{'x is \%3d, y is \%4.2f' \%(x, y) } - \end{block} - \small -\url{docs.python.org/lib/typesseq-strings.html}\\ -\end{frame} - -\begin{frame} - {A classic problem} - \begin{block} - {Interchange values} - How to interchange values of two variables? - \end{block} - \pause - \begin{block}{Note:} - This Python idiom works for all types of variables.\\ -They need not be of the same type! - \end{block} - \inctime{30} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 25 m+ Interlude break 5 mins, running 60m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\subsection{Control flow} -\begin{frame} - \frametitle{Control flow constructs} - \begin{itemize} - \item \kwrd{if/elif/else}: branching - \item \kwrd{while}: looping - \item \kwrd{for}: iterating - \item \kwrd{break, continue}: modify loop - \item \kwrd{pass}: syntactic filler - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic conditional flow} - \begin{lstlisting} -In [21]: a = 7 -In [22]: b = 8 -In [23]: if a > b: - ....: print 'Hello' - ....: else: - ....: print 'World' - ....: - ....: -World - \end{lstlisting} - Let us switch to creating a file -\end{frame} - -\begin{frame} - {Creating python files} - \begin{itemize} - \item aka scripts - \item use your editor - \item extension \typ{.py} - \item run with \texttt{python hello.py} at the command line - \item in IPython using \kwrd{\%run} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{If...elif...else} example} -\begin{lstlisting} -x = int(raw_input("Enter an integer:")) -if x < 0: - print 'Be positive!' -elif x == 0: - print 'Zero' -elif x == 1: - print 'Single' -else: - print 'More' -\end{lstlisting} -\end{frame} - -\begin{frame}{Simple IO} - \begin{block} - {Console Input} - \texttt{raw\_input()} waits for user input.\\Prompt string is optional.\\ - All keystrokes are Strings!\\\texttt{int()} converts string to int. - \end{block} - \begin{block} - {Console output} - \texttt{print} is straight forward. Note the distinction between \texttt{print x} and \texttt{print x,} - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic looping} - \begin{lstlisting} -# Fibonacci series: -# the sum of two elements -# defines the next -a, b = 0, 1 -while b < 10: - print b, - a, b = b, a + b - -\end{lstlisting} -\typ{1 1 2 3 5 8}\\ -\alert{Recall it is easy to write infinite loops with \kwrd{while}} - \inctime{20} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 20 m, running 80m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{Session Summary} -\begin{frame}{So what have we learnt so far?} - \begin{itemize} - \item The interactive interpreter - \item Basic Data Types - \item Creating and running a Python script - \item \kwrd{if/elif/else} - \item Simple IO - \item Basic Looping with \kwrd{while} - \end{itemize} -\end{frame} -\end{document} diff -r ae070c133120 -r 24992ab48f2b day1/Session-2.tex --- a/day1/Session-2.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,502 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -%\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\texttt{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -%%% This is from Fernando's setup. -% \usepackage{color} -% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} -% % Use and configure listings package for nicely formatted code -% \usepackage{listings} -% \lstset{ -% language=Python, -% basicstyle=\small\ttfamily, -% commentstyle=\ttfamily\color{blue}, -% stringstyle=\ttfamily\color{orange}, -% showstringspaces=false, -% breaklines=true, -% postbreak = \space\dots -% } - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Python:\\Functions and basic data structures} - -\author[FOSSEE Team] {Asokan Pichai\\Prabhu Ramachandran} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {10, October 2009\\Day 1, Session 2} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} -%\logo{\pgfuseimage{iitmlogo}} - - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each subsection: -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,subsections] - \end{frame} -} - - -% If you wish to uncover everything in a step-wise fashion, uncomment -% the following command: -%\beamerdefaultoverlayspecification{<+->} - -%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\section{Control Flow} - -\subsection{Exercises} -\begin{frame} - \frametitle{Problem set 1} - \begin{itemize} - \item All the problems can be\\ - solved using \kwrd{if} and \kwrd{while} - \end{itemize} -\end{frame} - -\begin{frame}{Problem 1.1} - Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ -\vspace*{0.2in} -\emphbar{These are called $Armstrong$ numbers.} -\end{frame} - -\begin{frame}{Problem 1.2 - Collatz sequence} -\begin{enumerate} - \item Start with an arbitrary (positive) integer. - \item If the number is even, divide by 2; if the number is odd, multiply by 3 and add 1. - \item Repeat the procedure with the new number. - \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. -\end{enumerate} - Write a program that accepts the starting value and prints out the Collatz sequence. - -\end{frame} - -\begin{frame}[fragile]{Problem 1.4} - Write a program that prints the following pyramid on the screen. - \begin{lstlisting} -1 -2 2 -3 3 3 -4 4 4 4 - \end{lstlisting} -The number of lines must be obtained from the user as input.\\ -\pause -\emphbar{When can your code fail?} -\only<2->{\inctime{20}} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 20 m, running 20m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{Functions} -\subsection{Defining} -\begin{frame}[fragile] -\frametitle{Functions: Definition} -\begin{itemize} - \item \kwrd{def} keyword - \item -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Functions: examples} - \begin{lstlisting} -In [35]: def plot_sinx(): - ....: x = linspace(0, 2*pi, 100) - ....: plt.plot(x, sin(x)) - ....: plt.show() - ....: - -In [36]: plot_sinx() - \end{lstlisting} -\pause -\emphbar{What about \% formatting?} -\end{frame} - -\begin{frame}[fragile] - {What does this function do?} - \begin{lstlisting} -def what( n ): - if n < 0: n = -n - while n > 0: - if n % 2 == 1: - return False - n /= 10 - return True - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - {What does this function do?} -\begin{lstlisting} -def what( n ): - i = 1 - while i * i < n: - i += 1 - return i * i == n, i - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - {What does this function do?} - \begin{lstlisting} -def what( n, x ): - z = 1.0 - if n < 0: - x = 1.0 / x - n = -n - while n > 0: - if n % 2 == 1: - z *= x - n /= 2 - x *= x - return z - \end{lstlisting} -\end{frame} - -\subsection{Built-in functions} -\begin{frame} - {Before writing a function} - \begin{itemize} - \item Variety of builtin functions are available - \item \typ{abs, any, all, len, max, min} - \item \typ{pow, range, sum, type} - \item Refer here: - \url{http://docs.python.org/library/functions.html} - \end{itemize} - \inctime{10} -\end{frame} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 10 m, running 30m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\subsection{Exercises} -\begin{frame}{Problem set 2: Problem 2.1} - Write a function to return the gcd of two numbers. -\end{frame} - -\begin{frame}{Problem 2.2} -Write a program to print all primitive pythagorean triads (a, b, c) where a, b are in the range 1---100 \\ -A pythagorean triad $(a,b,c)$ has the property $a^2 + b^2 = c^2$.\\By primitive we mean triads that do not `depend' on others. For example, (4,3,5) is a variant of (3,4,5) and hence is not primitive. And (10,24,26) is easily derived from (5,12,13) and is also not primitive. -\end{frame} - -\begin{frame}{Problem 2.3} - Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\newline\\\emph{For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square).} -\end{frame} - -\begin{frame}{Problem 2.4} - The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. For example, aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.\\ - Write a function that returns the aliquot number of a given number. -\end{frame} - -\begin{frame}{Problem 2.5} - A pair of numbers (a, b) is said to be \alert{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ - Example: \texttt{220, 284}\\ - Write a program that prints all four digit amicable pairs. - \inctime{25} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 25 m, running 55m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{Lists} - -\subsection{Manipulating} -\begin{frame}[fragile] - \frametitle{List creation and indexing} -\begin{lstlisting} ->>> a = [] # An empty list. ->>> a = [1, 2, 3, 4] # More useful. ->>> len(a) -4 ->>> a[0] + a[1] + a[-1] -7 -\end{lstlisting} - \begin{itemize} - \item Indices start with ? - \item Negative indices indicate ? - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{List: slices} - \begin{itemize} - \item Slicing is a basic operation - \item \typ{list[initial:final:step]} - \item The step is optional - \end{itemize} -\begin{lstlisting} ->>> a[1:3] # A slice. -[2, 3] ->>> a[1:-1] -[2, 3] ->>> a[1:] == a[1:-1] -False -\end{lstlisting} -Explain last result -\end{frame} - -\begin{frame}[fragile] - \frametitle{List: more slices} -\begin{lstlisting} ->>> a[0:-1:2] # Notice the step! -[1, 3] ->>> a[::2] -[1, 3] ->>> a[-1::-1] -\end{lstlisting} -What do you think the last one will do? - \emphbar{Strings also use same indexing and slicing.} -\end{frame} - -\begin{frame}[fragile] - \frametitle{List: examples} -\begin{lstlisting} ->>> a = [1, 2, 3, 4] ->>> a[:2] -[1, 2] ->>> a[0:-1:2] -[1, 3] -\end{lstlisting} -\pause -\alert{Lists are mutable (unlike strings)} -\begin{lstlisting} ->>> a[1] = 20 ->>> a -[1, 20, 3, 4] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Lists are mutable and heterogenous} -\begin{lstlisting} ->>> a = ['spam', 'eggs', 100, 1234] ->>> a[2] = a[2] + 23 ->>> a -['spam', 'eggs', 123, 1234] ->>> a[0:2] = [1, 12] # Replace items ->>> a -[1, 12, 123, 1234] ->>> a[0:2] = [] # Remove items ->>> a.append( 12345 ) ->>> a -[123, 1234, 12345] -\end{lstlisting} -\inctime{10} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 10 m, running 65m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\subsection{Methods} -\begin{frame}[fragile] - \frametitle{List methods} -\begin{lstlisting} ->>> a = ['spam', 'eggs', 1, 12] ->>> a.reverse() # in situ ->>> a -[12, 1, 'eggs', 'spam'] ->>> a.append(['x', 1]) ->>> a -[12, 1, 'eggs', 'spam', ['x', 1]] ->>> a.extend([1,2]) # Extend the list. ->>> a.remove( 'spam' ) ->>> a -[12, 1, 'eggs', ['x', 1], 1, 2] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{List containership} - \begin{lstlisting} ->>> a = ['cat', 'dog', 'rat', 'croc'] ->>> 'dog' in a -True ->>> 'snake' in a -False ->>> 'snake' not in a -True ->>> 'ell' in 'hello world' -True - \end{lstlisting} - \inctime{5} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 5 m, running 70m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{Tuples} -\begin{frame}[fragile] - \frametitle{Tuples: immutable} -\begin{lstlisting} ->>> t = (0, 1, 2) ->>> print t[0], t[1], t[2], t[-1] -0 1 2 2 ->>> t[0] = 1 -Traceback (most recent call last): - File "", line 1, in ? -TypeError: object does not support -item assignment -\end{lstlisting} -\begin{itemize} - \item Multiple return values are actually a tuple. - \item Exchange is tuple (un)packing -\end{itemize} -\inctime{5} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 5 m, running 75m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{for and range()} -\begin{frame}[fragile] - \frametitle{\typ{range()} function} - \begin{lstlisting} ->>> range(7) -[0, 1, 2, 3, 4, 5, 6] ->>> range( 3, 9) -[3, 4, 5, 6, 7, 8] ->>> range( 4, 17, 3) -[4, 7, 10, 13, 16] ->>> range( 5, 1, -1) -[5, 4, 3, 2] ->>> range( 8, 12, -1) -[] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{for\ldots range(\ldots)} idiom} - \begin{lstlisting} -In [83]: for i in range(5): - ....: print i, i * i - ....: - ....: -0 0 -1 1 -2 4 -3 9 -4 16 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{for}: the list companion} - - \begin{lstlisting} -In [84]: a = ['a', 'b', 'c'] -In [85]: for x in a: - ....: print x, chr( ord(x) + 10 ) - ....: -a k -b l -c m - \end{lstlisting} - Iterating over the list and not the index + reference\\ - what if you want the index? -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{for}: the list companion} - \begin{lstlisting} -In [89]: for p, ch in enumerate( a ): - ....: print p, ch - ....: - ....: -0 a -1 b -2 c - \end{lstlisting} -Try: \typ{print enumerate(a)} -\inctime{10} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 10 m, running 85m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\begin{frame} - \frametitle{What did we learn?} - \begin{itemize} - \item Control flow in action - \item Functions - \item Manipulating Lists - \item Tuples - \item range() function - \item for loops - \item for...range() idiom - \end{itemize} -\end{frame} -\end{document} diff -r ae070c133120 -r 24992ab48f2b day1/Session-3.tex --- a/day1/Session-3.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,522 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -%\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\texttt{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -%%% This is from Fernando's setup. -% \usepackage{color} -% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} -% % Use and configure listings package for nicely formatted code -% \usepackage{listings} -% \lstset{ -% language=Python, -% basicstyle=\small\ttfamily, -% commentstyle=\ttfamily\color{blue}, -% stringstyle=\ttfamily\color{orange}, -% showstringspaces=false, -% breaklines=true, -% postbreak = \space\dots -% } - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Python:\\Modular Code, Handling Files and Objects} - -\author[FOSSEE Team] {Asokan Pichai\\Prabhu Ramachandran} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {10, October 2009\\Day 1, Session 3} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} -%\logo{\pgfuseimage{iitmlogo}} - - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each section: -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection] - \end{frame} -} - - -% If you wish to uncover everything in a step-wise fashion, uncomment -% the following command: -%\beamerdefaultoverlayspecification{<+->} - -%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\section{\typ{for}, Lists and Tuples} - -\begin{frame}{Quick Recap} - \begin{itemize} - \item List indexing and slicing - \item The \kwrd{range()} function - \item \kwrd{for} - \item Iterating lists and tuples using \kwrd{for} and \kwrd{range()} - \end{itemize} -\end{frame} - -\begin{frame}{Problem 3.1} - Which of the earlier problems is simpler when we use \kwrd{for} instead of \kwrd{while}? -\end{frame} - -\begin{frame}{Problem 3.2} - Given an empty chessboard and one Bishop placed in any square, say (r, c), generate the list of all squares the Bishop could move to. -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem 3.3} - - Given two real numbers \typ{a, b}, and an integer \typ{N}, write a - function named \typ{linspace( a, b, N)} that returns an ordered list - of \typ{N} points starting with \typ{a} and ending in \typ{b} and - equally spaced.\\ - - For example, \typ{linspace(0, 5, 11)}, should return, \\ -\begin{lstlisting} -[ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, - 3.0 , 3.5, 4.0 , 4.5, 5.0 ] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem 3.4} - -Use the \typ{linspace} function and generate a list of N tuples of the form\\ -\typ{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions,\begin{itemize} - \item \typ{f(x) = sin(x)} - \item \typ{f(x) = sin(x) + sin(10*x)}. -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem 3.5} - - Using the tuples generated earlier, determine the intervals where the roots of the functions lie. - - \inctime{15} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 15 m, running 185m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{Parsing} - -\begin{frame}[fragile] - \frametitle{Simple tokenizing and parsing} - \begin{lstlisting} -s = """The quick brown fox jumped - over the lazy dog""" -for word in s.split(): - print word.capitalize() - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem 4.1} - Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \\ - \begin{lstlisting} - [1,3,4,5,6,7,12,15,18,19,20,21] - \end{lstlisting} -\end{frame} - -\section{Input/Output} - -\begin{frame}[fragile] - \frametitle{File handling} -\begin{lstlisting} ->>> f = open('/path/to/file_name') ->>> data = f.read() # Read entire file. ->>> line = f.readline() # Read one line. ->>> f.close() # close the file. -\end{lstlisting} -Writing files -\begin{lstlisting} ->>> f = open('/path/to/file_name', 'w') ->>> f.write('hello world\n') ->>> f.close() -\end{lstlisting} -\begin{itemize} - \item Everything read or written is a string -\end{itemize} -\emphbar{Try \typ{file?} for more help} -\end{frame} - -\begin{frame}[fragile] - \frametitle{File and \kwrd{for}} -\begin{lstlisting} -$ cat dummyfile -One 1 -Two 2 -Three 3 -Four 4 -Five 5 -Six 6 -Seven 7 -Eight 8 -Nine 9 -Ten 10 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{File and \kwrd{for}} -\begin{lstlisting} ->>> f = open('dummyfile') ->>> for line in f: -... print line -... -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{File and \kwrd{for}} -\begin{lstlisting} -In [1]: f = open('dummyfile') - -In [2]: for line in f: - ...: print line - ...: -\end{lstlisting} - -\begin{columns} - \column{0.3\textwidth} - -\begin{lstlisting} -One 1 - -Two 2 - -Three 3 -\end{lstlisting} - \column{0.6\textwidth} -\pause -\begin{block}{What happens when ...} -the \kwrd{print line} is replaced by \kwrd{print line,} -\end{block} -\end{columns} -\ldots -\end{frame} - -\begin{frame}{Problem 4.2} - The given file has lakhs of records in the form:\\ - \typ{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}\\ - Some entries may be empty. Read the data from this file and print the - name of the student with the maximum total marks. -\end{frame} - -\begin{frame}{Problem 4.3} - For the same data file compute the average marks in different - subjects, the student with the maximum mark in each subject and also - the standard deviation of the marks. Do this efficiently. - - \inctime{30} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 30 m, running 215m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{Modules} - -\begin{frame}[fragile] - {Modules} -\begin{lstlisting} ->>> sqrt(2) -Traceback (most recent call last): - File "", line 1, in -NameError: name 'sqrt' is not defined ->>> import math ->>> math.sqrt(2) -1.4142135623730951 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - {Modules} - \begin{itemize} - \item The \kwrd{import} keyword ``loads'' a module - \item One can also use: - \begin{lstlisting} ->>> from math import sqrt ->>> from math import * - \end{lstlisting} - \item What is the difference? - \item \alert{Use the latter only in interactive mode} - \end{itemize} - \emphbar{Package hierarchies} - \begin{lstlisting} ->>> from os.path import exists - \end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Modules: Standard library} - \begin{itemize} - \item Very powerful, ``Batteries included'' - \item Some standard modules: - \begin{itemize} - \item Math: \typ{math}, \typ{random} - \item Internet access: \typ{urllib2}, \typ{smtplib} - \item System, Command line arguments: \typ{sys} - \item Operating system interface: \typ{os} - \item Regular expressions: \typ{re} - \item Compression: \typ{gzip}, \typ{zipfile}, and \typ{tarfile} - \item And a whole lot more! - \end{itemize} - \item Check out the Python Library reference: - \url{http://docs.python.org/library/} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - {Modules of special interest} - \begin{description}[matplotlibfor2d] - - \item[\typ{numpy}] Efficient, powerful numeric arrays - - \item[\typ{matplotlib}] Easy, interactive, 2D plotting - - \item[\typ{scipy}] statistics, optimization, integration, linear - algebra, Fourier transforms, signal and image processing, - genetic algorithms, ODE solvers, special functions, and more - - \item[Mayavi] Easy, interactive, 3D plotting - - \end{description} -\end{frame} - -\begin{frame}[fragile] - {Creating your own modules} - \begin{itemize} - \item Define variables, functions and classes in a file with a - \typ{.py} extension - \item This file becomes a module! - \item Accessible when in the current directory - \item Use \typ{cd} in IPython to change directory - - \item Naming your module - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Modules: example} - \begin{lstlisting} -# --- arith.py --- -def gcd(a, b): - if a%b == 0: return b - return gcd(b, a%b) -def lcm(a, b): - return a*b/gcd(a, b) -# ------------------ ->>> import arith ->>> arith.gcd(26, 65) -13 ->>> arith.lcm(26, 65) -130 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem 5.1} - - Put all the functions you have written so far as part of the problems - into one module called \typ{bprim.py} and use this module from IPython. - -\inctime{25} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 25 m, running 230m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{Coding Style} -\begin{frame}{Readability and Consistency} - \begin{itemize} - \item Readability Counts!\\Code is read more often than its written. - \item Consistency! - \item Know when to be inconsistent. - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Code Layout} - \begin{itemize} - \item Indentation - \item Tabs or Spaces?? - \item Maximum Line Length - \item Blank Lines - \item Encodings - \end{itemize} -\end{frame} - -\begin{frame}{Whitespaces in Expressions} - \begin{itemize} - \item When to use extraneous whitespaces?? - \item When to avoid extra whitespaces?? - \item Use one statement per line - \end{itemize} -\end{frame} - -\begin{frame}{Comments} - \begin{itemize} - \item No comments better than contradicting comments - \item Block comments - \item Inline comments - \end{itemize} -\end{frame} - -\begin{frame}{Docstrings} - \begin{itemize} - \item When to write docstrings? - \item Ending the docstrings - \item One liner docstrings - \end{itemize} -More information at PEP8: http://www.python.org/dev/peps/pep-0008/ -\inctime{10} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% TIME: 10 m, running 240m -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{Objects} -\begin{frame}{Objects in general} - \begin{itemize} - \item What is an Object? (Types and classes) - \item identity - \item type - \item method - \end{itemize} -\end{frame} - -\begin{frame}{Almost everything is an Object!} - \begin{itemize} - \item \typ{list} - \item \typ{tuple} - \item \typ{string} - \item \typ{dictionary} - \item \typ{function} - \item Of course, user defined class objects! - \end{itemize} -\end {frame} - -\begin{frame}{Using Objects} - \begin{itemize} - \item Creating Objects: Initialization - \item Object Manipulation: Object methods and ``.'' operator - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{IPython Examples} - \begin{lstlisting} -In [1]: l = [] #Initialising a list object -In [2]: l? -In [3]: l. - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Objects provide consistency} - \small - \begin{lstlisting} -for element in (1, 2, 3): - print element -for key in {'one':1, 'two':2}: - print key -for char in "123": - print char -for line in open("myfile.txt"): - print line -for line in urllib2.urlopen('http://site.com'): - print line - \end{lstlisting} -\end{frame} - -\begin{frame}{And the winner is \ldots OBJECTS!} - All objects providing a similar inteface can be used the same way.\\ - Functions (and others) are first-class objects. Can be passed to and returned from functions. - \inctime{10} -\end{frame} - -\section{Summary} - -\begin{frame}{What have we learnt so far?} - \begin{itemize} - \item Operating on lists and tuples using \kwrd{for} - \item Simple string tokenizing and parsing - \item Writing to and Reading from files using \kwrd{for} - \item Using and writing Python Modules - \item Coding Style - \item Objects in Python - \end{itemize} -\end{frame} - -\end{document} diff -r ae070c133120 -r 24992ab48f2b day1/Session-4.tex --- a/day1/Session-4.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,418 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -%\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -\usepackage{pgf} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\texttt{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -%%% This is from Fernando's setup. -% \usepackage{color} -% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} -% % Use and configure listings package for nicely formatted code -% \usepackage{listings} -% \lstset{ -% language=Python, -% basicstyle=\small\ttfamily, -% commentstyle=\ttfamily\color{blue}, -% stringstyle=\ttfamily\color{orange}, -% showstringspaces=false, -% breaklines=true, -% postbreak = \space\dots -% } - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Python:\\Advanced Python data structures, Functions and Debugging} - -\author[FOSSEE Team] {Asokan Pichai\\Prabhu Ramachandran} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {10, October 2009\\Day 1, Session 4} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} -%\logo{\pgfuseimage{iitmlogo}} - - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each subsection: -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,subsections] - \end{frame} -} - - -% If you wish to uncover everything in a step-wise fashion, uncomment -% the following command: -%\beamerdefaultoverlayspecification{<+->} - -%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \titlepage -\end{frame} - -\section{Advanced Data structures} - -\subsection{Dictionary} -\begin{frame}{Dictionary} - \begin{itemize} - \item lists and tuples index: 0 \ldots n - \item dictionaries index using strings - \item \typ{ d = \{ ``Hitchhiker's guide'' : 42, ``Terminator'' : ``I'll be back''\}} - \item \typ{d[``Terminator''] => ``I'll be back''} - \item aka associative array, key-value pair, hashmap, hashtable \ldots - \item what can be keys? - \end{itemize} -\end{frame} - -\begin{frame}{Dictionary \ldots } - \begin{itemize} - \item \alert{Unordered} - \begin{block}{Standard usage} - for key in dict:\\ - \ \ \ \ print dict[key] - \end{block} - \item \typ{d.keys()} returns a list - \item can we have duplicate keys? - \end{itemize} - \inctime{5} -\end{frame} - -\begin{frame} {Problem Set 6.1} - \begin{description} -\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. - \item[6.1.2] Count word frequencies in a file. - \item[6.1.3] Find the most used Python keywords in your Python code (import keyword). -\end{description} - -\inctime{10} -\end{frame} - -\subsection{Set} -\begin{frame}[fragile] - \frametitle{Set} - \begin{itemize} - \item Simplest container, mutable - \item No ordering, no duplicates - \item usual suspects: union, intersection, subset \ldots - \item >, >=, <, <=, in, \ldots - \end{itemize} - \begin{lstlisting} ->>> f10 = set([1,2,3,5,8]) ->>> p10 = set([2,3,5,7]) ->>> f10|p10 -set([1, 2, 3, 5, 7, 8]) ->>> f10&p10 -set([2, 3, 5]) ->>> f10-p10 -set([8, 1]) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Set} - \begin{lstlisting} ->>> p10-f10, f10^p10 -set([7]), set([1, 7, 8]) ->>> set([2,3]) < p10 -True ->>> set([2,3]) <= p10 -True ->>> 2 in p10 -True ->>> 4 in p10 -False ->>> len(f10) -5 -\end{lstlisting} -\inctime{5} -\end{frame} - -\begin{frame} - \frametitle{Problem set 6.2} - \begin{description} - \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? - \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. -\end{description} -\inctime{10} -\end{frame} - - -\section{Functions Reloaded!} -\begin{frame}[fragile] - \frametitle{Advanced functions} - \begin{itemize} - \item default args - \item var args - \item keyword args - \item scope - \item \typ{global} - \end{itemize} -\end{frame} - -\subsection{Default arguments} -\begin{frame}[fragile] - \frametitle{Functions: default arguments} - \small - \begin{lstlisting} -def ask_ok(prompt, complaint='Yes or no!'): - while True: - ok = raw_input(prompt) - if ok in ('y', 'ye', 'yes'): - return True - if ok in ('n', 'no', 'nop', - 'nope'): - return False - print complaint - -ask_ok('?') -ask_ok('?', '[Y/N]') - \end{lstlisting} -\end{frame} - -\subsection{Keyword arguments} -\begin{frame}[fragile] - \frametitle{Functions: keyword arguments} - \small - \begin{lstlisting} -def ask_ok(prompt, complaint='Yes or no!'): - while True: - ok = raw_input(prompt) - if ok in ('y', 'ye', 'yes'): - return True - if ok in ('n', 'no', 'nop', - 'nope'): - return False - print complaint - -ask_ok(prompt='?') -ask_ok(prompt='?', complaint='[y/n]') -ask_ok(complaint='[y/n]', prompt='?') -\end{lstlisting} -\inctime{15} -\end{frame} - -\section{Functional programming} -\begin{frame}[fragile] - \frametitle{Functional programming} - \begin{itemize} - \item What is the basic idea? - \item Why is it interesting? - \item \typ{map, reduce, filter} - \item list comprehension - \item generators - \end{itemize} -\end{frame} - -\subsection{List comprehensions} -\begin{frame}[fragile] - \frametitle{List Comprehensions} -Lets say we want to squares of all the numbers from 1 to 100 - \begin{lstlisting} -squares = [] -for i in range(1, 100): - squares.append(i * i) - \end{lstlisting} - \begin{lstlisting} -# list comprehension -squares = [i*i for i in range(1, 100)] - \end{lstlisting} -Which is more readable? -\end{frame} - -\begin{frame}[fragile] - \frametitle{List Comprehensions} -What if you had a more complex function? -Lets say we want squares of numbers from 1 to 100 ending in 1, 2, 5, 7 only - \begin{lstlisting} -squares = [] -for i in range(1, 100): - if i % 10 in [1, 2, 5, 7]: - squares.append(i * i) - \end{lstlisting} - \begin{lstlisting} -# list comprehension -squares = [i*i for i in range(1, 100) - if i % 10 in [1, 2, 5, 7]] - \end{lstlisting} -Which is more readable? -\inctime{15} -\end{frame} - -\section{Debugging} -\subsection{Errors and Exceptions} -\begin{frame}[fragile] - \frametitle{Errors} - \begin{lstlisting} ->>> while True print 'Hello world' - \end{lstlisting} -\pause - \begin{lstlisting} - File "", line 1, in ? - while True print 'Hello world' - ^ -SyntaxError: invalid syntax -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exceptions} - \begin{lstlisting} ->>> print spam -\end{lstlisting} -\pause -\begin{lstlisting} -Traceback (most recent call last): - File "", line 1, in -NameError: name 'spam' is not defined -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exceptions} - \begin{lstlisting} ->>> 1 / 0 -\end{lstlisting} -\pause -\begin{lstlisting} -Traceback (most recent call last): - File "", line 1, in -ZeroDivisionError: integer division -or modulo by zero -\end{lstlisting} -\end{frame} - -\subsection{Strategy} -\begin{frame}[fragile] - \frametitle{Debugging effectively} - \begin{itemize} - \item \kwrd{print} based strategy - \item Process: - \end{itemize} -\pgfimage[interpolate=true,width=5cm,height=5cm]{DebugginDiagram.png} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Debugging effectively} - \begin{itemize} - \item Using \typ{\%debug} in IPython - \end{itemize} -\end{frame} - -\begin{frame}[fragile] -\frametitle{Debugging in IPython} -\small -\begin{lstlisting} -In [1]: import mymodule -In [2]: mymodule.test() ---------------------------------------------- -NameError Traceback (most recent call last) - in () -mymodule.py in test() - 1 def test(): -----> 2 print spam -NameError: global name 'spam' is not defined - -In [3]: %debug -> mymodule.py(2)test() - 0 print spam -ipdb> -\end{lstlisting} -\inctime{15} -\end{frame} - -\subsection{Exercise} -\begin{frame}[fragile] -\frametitle{Debugging: Exercise} -\small -\begin{lstlisting} -import keyword -f = open('/path/to/file') - -freq = {} -for line in f: - words = line.split() - for word in words: - key = word.strip(',.!;?()[]: ') - if keyword.iskeyword(key): - value = freq[key] - freq[key] = value + 1 - -print freq -\end{lstlisting} -\inctime{10} -\end{frame} - -\begin{frame} - \frametitle{What did we learn?} - \begin{itemize} - \item Dictionaries - \item Sets - \item Default and keyword arguments - \item Functional Programming, list comprehensions - \item Errors and Exceptions in Python - \item Debugging: \%debug in IPython - \end{itemize} -\end{frame} -\end{document} diff -r ae070c133120 -r 24992ab48f2b day1/debug_exercise.py --- a/day1/debug_exercise.py Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,13 +0,0 @@ -import keyword -f = open('/path/to/file') - -freq = {} -for line in f: - words = line.split() - for word in words: - key = word.strip(',.!;?()[]: ') - if keyword.iskeyword(key): - value = freq[key] - freq[key] = value + 1 - -print freq diff -r ae070c133120 -r 24992ab48f2b day1/dummyfile --- a/day1/dummyfile Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,10 +0,0 @@ -One 1 -Two 2 -Three 3 -Four 4 -Five 5 -Six 6 -Seven 7 -Eight 8 -Nine 9 -Ten 10 \ No newline at end of file diff -r ae070c133120 -r 24992ab48f2b day2/EngPython.tex --- a/day2/EngPython.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1987 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2008, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -%\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\texttt{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -%%% This is from Fernando's setup. -% \usepackage{color} -% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} -% % Use and configure listings package for nicely formatted code -% \usepackage{listings} -% \lstset{ -% language=Python, -% basicstyle=\small\ttfamily, -% commentstyle=\ttfamily\color{blue}, -% stringstyle=\ttfamily\color{orange}, -% showstringspaces=false, -% breaklines=true, -% postbreak = \space\dots -% } - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Python,\\a great programming toolkit:\\ -numerics and plotting} - -\author[Asokan \& Prabhu] {Asokan Pichai\\Prabhu Ramachandran} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {26, July 2009} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} -%\logo{\pgfuseimage{iitmlogo}} - - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each subsection: -\AtBeginSubsection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -% If you wish to uncover everything in a step-wise fashion, uncomment -% the following command: -%\beamerdefaultoverlayspecification{<+->} - -%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \titlepage -\end{frame} -\begin{frame} - {Acknowledgements} - \begin{center} - This program is conducted by\\ - IIT, Bombay\\ - through CDEEP\\ - as part of the open source initiatives\\ - under the aegis of\\ - \alert{National Mission on Education through ICT,} \\ - Ministry of HRD. - \end{center} -\end{frame} - -\begin{frame} - \frametitle{Outline} - \tableofcontents - % You might wish to add the option [pausesections] -\end{frame} - -\begin{frame}{Goal of the Workshop} - - At the end of this program, successful participants will be able - to use python as their scripting and problem solving language. - Aimed at Engg. students--focus on basic numerics and plotting-- - but should serve a similar purpose for others.\\ - - At the minimum you will be able to use Python for your plotting immediately. - -\end{frame} - -\begin{frame}{Checklist} - - \begin{description} - \item[pylab] matplotlib interface - \item[numpy] Array computing - \item[scipy] numerical work - \item[mayavi] \typ{enthought.mayavi}: 3D viz. - \end{description} -\end{frame} - -\section{30000 feet view} -\begin{frame}{Lets see what we can do!} - \huge - Hold on to your seatbelts -\end{frame} - -\begin{frame} - {That was done by\ldots} - \begin{description}[CalisthenicsIsAnArt] - \item[Arrays] 2--3 lines; 5 minutes to learn - \item[2D plots] 5 lines; 10 minutes to learn - \item[Simple 3D plots] 5 lines; 10 minutes to learn; GUI - exploration! - \item[Complex plots] relatively short (10-15 lines); more time to master; - \end{description} - \inctime{15} -\end{frame} - -\section{Matplotlib} - -\subsection{Basic \typ{numpy} } - -\newcommand{\num}{\texttt{numpy}} - -\begin{frame} - \frametitle{The \num\ module} - \begin{itemize} - \item Why? - \item What: - \begin{itemize} - \item An efficient and powerful array type for various common data - types - \item Abstracts out the most commonly used standard operations on - arrays - \end{itemize} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Examples of \num} -\begin{lstlisting} -# Simple array math example ->>> from numpy import * ->>> a = array([1,2,3,4]) ->>> b = array([2,3,4,5]) ->>> a*2 + b + 1 # Basic math! -array([5, 8, 11, 14]) -# Pi and e are defined. ->>> x = linspace(0.0, 10.0, 1000) ->>> x *= 2*pi/10 # inplace. -# apply functions to array. ->>> y = sin(x) -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Basic concepts} - \begin{itemize} - \item fixed size (\typ{arr.size}); - \item Same type (\typ{arr.dtype}) of data - \item arbitrary dimensionality - \item \typ{arr.shape}: size in each dimension - \item \alert{Note:} \typ{len(arr) != arr.size} in general - \item \alert{Note:} By default array operations are performed - \alert{elementwise} - \item Indices, slicing: just like lists - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{More examples of \num} -\vspace*{-8pt} -\begin{lstlisting} ->>> x = array([1., 2, 3, 4]) ->>> size(x) -4 ->>> x.dtype # What is a.dtype? -dtype('float64') ->>> x.shape -(4,) ->>> print rank(x), x.itemsize -1 8 ->>> x[0] = 10 ->>> print x[0], x[-1] -10.0 4.0 -\end{lstlisting} - -\inctime{10} -\end{frame} - - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -\subsection{Plotting with \typ{pylab}} - -\begin{frame} - {IPython's \typ{pylab} mode} -\begin{itemize} - \item \typ{pylab}: convenient 2D plotting interface to MPL - \item Immediate use: \typ{ipython -pylab} - \item Imports all of pylab for you! - \item Allows for interactive plotting -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic 2D plotting} - -\begin{lstlisting} ->>> x = linspace(0, 2*pi, 1000) ->>> plot(x, sin(x)) ->>> plot(x, sin(x), 'ro') ->>> xlabel(r'$\chi$', color='g') -# LaTeX markup! ->>> ylabel(r'sin($\chi$)', color='r') ->>> title('Simple figure', fontsize=20) ->>> savefig('/tmp/test.eps') -\end{lstlisting} -\begin{itemize} - \item Also: PNG, PDF, PS, EPS, SVG, PDF -\end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Basic plotting \ldots} -\begin{lstlisting} -# Set properties of objects: ->>> l, = plot(x, sin(x)) -# Why "l,"? ->>> setp(l, linewidth=2.0, color='r') ->>> l.set_linewidth(2.0) ->>> draw() # Redraw. ->>> setp(l) # Print properties ->>> clf() # Clear figure. ->>> close() # Close figure. -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Multiple figures} - -\begin{lstlisting} ->>> figure(1) ->>> plot(x, sin(x)) ->>> figure(2) ->>> plot(x, tanh(x)) ->>> figure(1) ->>> title('Easy as 1,2,3') -\end{lstlisting} - -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Legends and Annotation} -\begin{lstlisting} ->>> plot(x, cos(5*x), 'r--', - label='cosine') ->>> plot(x, sin(5*x), 'g--', - label='sine') ->>> legend() -# Or use: ->>> legend(['cosine', 'sine']) -# Annotation: ->>> text(1,0, '(1,0)') -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More commands \ldots} - \begin{lstlisting} -# semilog, loglog ->>> x = 10.**(-arange(100)*0.1) ->>> semilogx(x, x) ->>> semilogy(x, x) ->>> loglog(x, x) ->>> loglog(x, x*x) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More plots \ldots} - \begin{lstlisting} ->>> clf() ->>> t = arange(0.1, 4, 0.1) ->>> s = exp(-t) ->>> e = 0.1*abs(randn(len(s))) ->>> errorbar(t, s, e) -# Scatter plots ->>> clf() ->>> t = randn(len(e)) ->>> scatter(t, e, c=s) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Note: \typ{pylab} in Python scripts} -\begin{lstlisting} -import pylab -x = pylab.linspace(0, 20, 1000) -pylab.plot(x, pylab.sin(x)) - -# Can also use: -from pylab import linspace, sin, plot -\end{lstlisting} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\begin{frame}[fragile] - \frametitle{X-Y plot} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/xyplot} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -t1 = arange(0.0, 5.0, 0.1) -t2 = arange(0.0, 5.0, 0.02) -t3 = arange(0.0, 2.0, 0.01) -subplot(211) -plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', - t2, cos(2*pi*t2)*exp(-t2), 'k') -grid(True) -title('A tale of 2 subplots') -ylabel('Damped') -subplot(212) -plot(t3, cos(2*pi*t3), 'r--') -grid(True) -xlabel('time (s)') -ylabel('Undamped') -\end{lstlisting} - \end{block} - \end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Semi-log and log-log plots} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/log} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -dt = 0.01 -t = arange(dt, 20.0, dt) -subplot(311) -semilogy(t, exp(-t/5.0)) -ylabel('semilogy') -grid(True) -subplot(312) -semilogx(t, sin(2*pi*t)) -ylabel('semilogx') -grid(True) -# minor grid on too -gca().xaxis.grid(True, which='minor') -subplot(313) -loglog(t, 20*exp(-t/10.0), basex=4) -grid(True) -ylabel('loglog base 4 on x') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Errorbar} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/errorbar} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -t = arange(0.1, 4, 0.1) -s = exp(-t) -e = 0.1*abs(randn(len(s))) -f = 0.1*abs(randn(len(s))) -g = 2*e -h = 2*f -errorbar(t, s, [e,g], f, fmt='o') -xlabel('Distance (m)') -ylabel('Height (m)') -title('Mean and standard error '\ - 'as a function of distance') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Histogram} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/histogram} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -mu, sigma = 100, 15 -x = mu + sigma*randn(10000) -# the histogram of the data -n, bins, patches = hist(x, 100, normed=1) -# add a 'best fit' line -y = normpdf( bins, mu, sigma) -l = plot(bins, y, 'r--', linewidth=2) -xlim(40, 160) -xlabel('Smarts') -ylabel('P') -title(r'$\rm{IQ:}\/ \mu=100,\/ \sigma=15$') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Bar charts} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/barchart} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -N = 5 -menMeans = (20, 35, 30, 35, 27) -menStd = ( 2, 3, 4, 1, 2) -# the x locations for the groups -ind = arange(N) -# the width of the bars -width = 0.35 -p1 = bar(ind, menMeans, width, - color='r', yerr=menStd) -womenMeans = (25, 32, 34, 20, 25) -womenStd = ( 3, 5, 2, 3, 3) -p2 = bar(ind+width, womenMeans, width, - color='y', yerr=womenStd) -ylabel('Scores') -title('Scores by group and gender') -xticks(ind+width, - ('G1', 'G2', 'G3', 'G4', 'G5')) -xlim(-width,len(ind)) -yticks(arange(0,41,10)) -legend((p1[0], p2[0]), - ('Men', 'Women'), shadow=True) -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Pie charts} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.4in} - \includegraphics[height=2.0in, interpolate=true]{data/piechart} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -# make a square figure and axes -figure(1, figsize=(8,8)) -ax = axes([0.1, 0.1, 0.8, 0.8]) -labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' -fracs = [15,30,45, 10] -explode=(0, 0.05, 0, 0) -pie(fracs, explode=explode, labels=labels, - autopct='%1.1f%%', shadow=True) -title('Raining Hogs and Dogs', - bbox={'facecolor':'0.8', 'pad':5}) -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Scatter plots} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.4in} - \includegraphics[height=2in, interpolate=true]{data/scatter} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -N = 30 -x = 0.9*rand(N) -y = 0.9*rand(N) -# 0 to 10 point radiuses -area = pi*(10 * rand(N))**2 -volume = 400 + rand(N)*450 -scatter(x,y,s=area, marker='o', c=volume, - alpha=0.75) -xlabel(r'$\Delta_i$', size='x-large') -ylabel(r'$\Delta_{i+1}$', size='x-large') -title(r'Volume and percent change') -grid(True) -colorbar() -savefig('scatter') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Polar} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/polar} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -figure(figsize=(8,8)) -ax = axes([0.1, 0.1, 0.8, 0.8], - polar=True, - axisbg='#d5de9c') -r = arange(0,1,0.001) -theta = 2*2*pi*r -polar(theta, r, color='#ee8d18', lw=3) -# the radius of the grid labels -setp(ax.thetagridlabels, y=1.075) -title(r"$\theta=4\pi r", fontsize=20) -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Contours} - \begin{columns} - \column{0.45\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/contour} - \column{0.525\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -x = arange(-3.0, 3.0, 0.025) -y = arange(-2.0, 2.0, 0.025) -X, Y = meshgrid(x, y) -Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -# difference of Gaussians -Z = 10.0 * (Z2 - Z1) -im = imshow(Z, interpolation='bilinear', - origin='lower', - cmap=cm.gray, extent=(-3,3,-2,2)) -levels = arange(-1.2, 1.6, 0.2) -# label every second level -clabel(CS, levels[1::2], inline=1, - fmt='%1.1f', fontsize=14) -CS = contour(Z, levels, - origin='lower', - linewidths=2, - extent=(-3,3,-2,2)) -# make a colorbar for the contour lines -CB = colorbar(CS, shrink=0.8, extend='both') -title('Lines with colorbar') -hot(); flag() -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Velocity vectors} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/quiver} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -X,Y = meshgrid(arange(0,2*pi,.2), - arange(0,2*pi,.2) ) -U = cos(X) -V = sin(Y) -Q = quiver(X[::3, ::3], Y[::3, ::3], - U[::3, ::3], V[::3, ::3], - color='r', units='x', - linewidths=(2,), - edgecolors=('k'), - headaxislength=5 ) -qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', - fontproperties= - {'weight': 'bold'}) -axis([-1, 7, -1, 7]) -title('triangular head; scale '\ - 'with x view; black edges') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Maps} - \includegraphics[height=2.5in, interpolate=true]{data/plotmap} - \begin{center} - \tiny - For details see \url{http://matplotlib.sourceforge.net/screenshots/plotmap.py} - \end{center} -\end{frame} - - -\begin{frame} - \frametitle{More information} - \begin{itemize} - \item More information here: \url{http://matplotlib.sf.net} - \item \url{http://matplotlib.sf.net/tutorial.html} - \item \url{http://matplotlib.sf.net/screenshots.html} - \end{itemize} - - \inctime{25} -\end{frame} - -\begin{frame} - \frametitle{Problem set 1.0} - \begin{enumerate} - \item Write a function that plots any n-gon given \typ{n}. - \item Consider the logistic map, $f(x) = kx(1-x)$, plot it for - $k=2.5, 3.5$ and $4$ -\end{enumerate} -\end{frame} - -\begin{frame} - \frametitle{Problem set 1.1} - \begin{enumerate} - \item Consider the iteration $x_{n+1} = f(x_n)$ where $f(x) = - kx(1-x)$. Plot the successive iterates of this process. - \item Plot this using a cobweb plot as follows: - \begin{enumerate} - \item Start at $(x_0, 0)$ - \item Draw line to $(x_i, f(x_i))$; - \item Set $x_{i+1} = f(x_i)$ - \item Draw line to $(x_i, x_i)$ - \item Repeat from 2 for as long as you want - \end{enumerate} - \end{enumerate} -\end{frame} - -\begin{frame} - \frametitle{Problem set 1.2} - \begin{enumerate} - - \item Plot the Koch snowflake. Write a function to generate the - necessary points given the two points constituting a line. - \pause - \begin{enumerate} - \item Split the line into 4 segments. - \item The first and last segments are trivial. - \item To rotate the point you can use complex numbers, - recall that $z e^{j \theta}$ rotates a point $z$ in 2D - by $\theta$. - \item Do this for all line segments till everything is - done. - \end{enumerate} - \item Show rate of convergence for a first and second order finite - difference of sin(x) -\end{enumerate} -\inctime{30} -\end{frame} - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\begin{frame}[fragile] - \frametitle{More IPython features} - \begin{itemize} - \item Input and output caching: - \begin{itemize} - \item \verb+In+: a list of all entered input - \item \verb+Out+: a dict of all output - \item \verb+%hist [-n]+ macro shows previous history, \verb+-n+ - suppresses line number information - \end{itemize} - \item Log the session using \verb+%logstart+, \verb+%logon+ and - \verb+%logoff+ - \item Use \verb+;+ to suppress printing output - \item \verb+%time statement+ - \item \verb+%timeit [-n -r [-t|-c]] statement+ - - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More IPython features} - \begin{itemize} - \item \verb+%run [options] file[.py]+ -- running Python code - \item \verb+%prun+ runs a statement/expression under the profiler - \item \verb+%debug+: Helps with debugging after a crash - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More IPython features \ldots} - \begin{itemize} - \item \verb+%edit [options] [args]+: edit lines of code or file - specified in editor (configure editor via \verb+$EDITOR+) - \item \verb+%cd+ changes directory, see also \verb+%pushd, %popd, %dhist+ - \item Shell access - \begin{itemize} - \item \verb+!command+ runs a shell command and returns its output - \item \verb+files = !ls+ sets - \verb+files+ to all result of the \verb+ls+ command - \item \verb+!ls $files+ passes the \verb+files+ variable to the - shell command - \end{itemize} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More IPython features \ldots} - \begin{itemize} - \item \verb+%bookmark+: store a bookmarked location, for use with \verb+%cd+ - \item \verb+%save [options] filename n1-n2 n3-n4+: save lines to a - file - \item Can define and use profiles to setup IPython differently: - \verb+math, scipy, numeric, pysh+ etc. - \item \verb+%magic+: \alert{Show help on all magics} - \item Check out the \verb+%macro+ magic - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Problem set 2} - \begin{itemize} - \item Compare your linspace with that of numpy for 1 million - elements in terms of speed. -\end{itemize} -\inctime{10} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Debugging effectively} - - \begin{itemize} - \item \kwrd{print} based strategy - \item Process: Hypothesis, test, refine, rinse-repeat - \item Using \typ{\%debug} and \typ{\%pdb} in IPython - \end{itemize} - - \inctime{10} -\end{frame} - -\section{Debugging and testing} - -\begin{frame}[fragile] - \frametitle{Testing code with \typ{nosetests}} - - \begin{itemize} - \item Writing tests is really simple! - - \item Using nose - - \item Example! - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Nosetest} -\begin{lstlisting} -def gcd(a, b): - """Returns gcd of a and b, - handles only positive numbers.""" - if a%b == 0: return b - return gcd(b, a%b) -def lcm(a, b): - return a*b/gcd(a, b) - -if __name__ == '__main__': - import nose - nose.main() -\end{lstlisting} - - \inctime{10} -\end{frame} - -\section{NumPy and SciPy} - -\begin{frame} - {More Numpy} - - \begin{itemize} - \item Multi-dimensional arrays - \item Random number generation - \end{itemize} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Multi-dimensional arrays} -\begin{lstlisting} ->>> a = array([[ 0, 1, 2, 3], -... [10,11,12,13]]) ->>> a.shape # (rows, columns) -(2, 4) -# Accessing and setting values ->>> a[1,3] -13 ->>> a[1,3] = -1 ->>> a[1] # The second row -array([10,11,12,-1]) - -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Slicing arrays} -\begin{lstlisting} ->>> a = array([[1,2,3], [4,5,6], - [7,8,9]]) ->>> a[0,1:3] -array([2, 3]) ->>> a[1:,1:] -array([[5, 6], - [8, 9]]) ->>> a[:,2] -array([3, 6, 9]) -\end{lstlisting} -\end{frame} -\begin{frame}[fragile] - \frametitle{Striding arrays} -\begin{lstlisting} ->>> a[0::2,0::2] -array([[1, 3], - [7, 9]]) -# Slices are references to the -# same memory! -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Array creation functions} - \begin{itemize} - \item \typ{array(object, dtype=None, \ldots)} - \item \typ{arange(start, stop=None, step=1 \ldots)} - \item \typ{linspace(start, stop, num=50, \ldots)} - \item \typ{ones(shape, dtype=None, \ldots)} - \item \typ{zeros(shape, dtype=float,\ldots)} - \item \typ{identity(n)} - \item \typ{empty(shape, dtype=float,\ldots)} - \item \typ{ones\_like(x)}, - \item \typ{zeros\_like(x)}, \typ{empty\_like(x)} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Array math} - \begin{itemize} - \item Basic \alert{elementwise} math (given two arrays \typ{a, b}): - \typ{+, -, *, /, \%} - \item Inplace operators: \typ{a += b}, or \typ{add(a, b, - a)} etc. - \item Logical operations: \typ{equal (==)}, \typ{not\_equal (!=)}, - \typ{less (<)}, \typ{greater (>)} etc. - \item Trig and other functions: \typ{sin(x), arcsin(x), sinh(x), - exp(x), sqrt(x)} etc. - \item \typ{sum(x, axis=0), product(x, axis=0)} - \item \typ{dot(a, b)} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Advanced} - \begin{itemize} - \item Only scratched the surface of \num - \item Ufunc methods: \typ{reduce, accumulate, outer, reduceat} - \item Typecasting - \item More functions: \typ{take, choose, where, compress, - concatenate} - \item Array broadcasting and \typ{None} - \end{itemize} - \inctime{15} -\end{frame} - -\begin{frame} - {Intro to SciPy} - \begin{itemize} - \item \url{http://www.scipy.org} - \item Open source scientific libraries for Python - \item Based on NumPy - \end{itemize} - - \inctime{25} -\end{frame} - -\begin{frame} - \frametitle{SciPy} - \begin{itemize} - \item Provides: - \begin{itemize} - \item Linear algebra - \item Numerical integration - \item Fourier transforms - \item Signal processing - \item Special functions - \item Statistics - \item Optimization - \item Image processing - \item ODE solvers - \end{itemize} - \item Uses LAPACK, QUADPACK, ODEPACK, FFTPACK etc. from netlib - \end{itemize} -\end{frame} - - -\section{3D Plotting} - -\begin{frame} - \frametitle{Introduction to Mayavi} - \begin{itemize} - \item Most scientists not interested in details of visualization - \item Visualization of data files with a nice UI - \item Interactive visualization of data (think Matlab) - \item Embedding visualizations in applications - \item Customization - \end{itemize} - \pause - \begin{block}{The Goal} - Provide a \alert{flexible} library/app for every one of these needs! - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{mlab}} - \begin{columns} - \column{0.62\textwidth} - \hspace*{-0.45in} - \footnotesize -\begin{lstlisting} -from enthought.mayavi import mlab -from numpy import ogrid, sin - -x, y, z = ogrid[-10:10:100j, - -10:10:100j, - -10:10:100j] - -mlab.contour3d(sin(x*y*z)/(x*y*z)) -mlab.show() -\end{lstlisting} - \column{0.4\textwidth} - \hspace*{-0.1\linewidth} - \includegraphics[width=1.18\linewidth]{data/mlab.png} - \end{columns} -\end{frame} - -\begin{frame} - {A Look at the docs } - - \inctime{20} -\end{frame} - - -\section{Integration demo: Lorenz equations} - -\begin{frame} - \frametitle{Lorenz equation example} - \begin{eqnarray*} - \frac{d x}{dt} &=& s (y-x)\\ - \frac{d y}{d t} &=& rx -y -xz\\ - \frac{d z}{d t} &=& xy - bz\\ - \end{eqnarray*} - \begin{itemize} - \item Specifies the evolution of the system - \item Think: Velocity of a particle in 3D - \item Lets trace its path - \end{itemize} -\end{frame} - -\begin{frame} - {Interactive exploration} - - \inctime{25} -\end{frame} - - -\end{document} - -- Numpy arrays (30 mins) - - Matrices - - random number generation. - - Image manipulation: jigsaw puzzle. - - Monte-carlo integration. - - - - - -\begin{frame}[fragile] - \frametitle{More on functions} - \begin{itemize} - \item Support default and keyword arguments - \item Scope of variables in the function is local - \item Mutable items are \alert{passed by reference} - \item First line after definition may be a documentation string - (\alert{recommended!}) - \item Function definition and execution defines a name bound to the - function - \item You \emph{can} assign a variable to a function! - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Functions: default arguments} - \begin{lstlisting} -def ask_ok(prompt, retries=4, complaint='Yes or no!'): - while True: - ok = raw_input(prompt) - if ok in ('y', 'ye', 'yes'): - return True - if ok in ('n', 'no', 'nop', 'nope'): - return False - retries = retries - 1 - if retries < 0: - raise IOError, 'bad user' - print complaint - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Functions: keyword arguments} - \begin{lstlisting} -def parrot(voltage, state='a stiff', - action='voom', type='Norwegian Blue'): - print "-- This parrot wouldn't", action, - print "if you put", voltage, "Volts through it." - print "-- Lovely plumage, the", type - print "-- It's", state, "!" - -parrot(1000) -parrot(action = 'VOOOOOM', voltage = 1000000) -parrot('a thousand', state = 'pushing up the daisies') -parrot('a million', 'bereft of life', 'jump') -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Functions: arbitrary argument lists} - \begin{itemize} - \item Arbitrary number of arguments using \verb+*args+ or - \verb+*whatever+ - \item Keyword arguments using \verb+**kw+ - \item Given a tuple/dict how do you call a function? - \begin{itemize} - \item Using argument unpacking - \item For positional arguments: \verb+foo(*[5, 10])+ - \item For keyword args: \verb+foo(**{'a':5, 'b':10})+ - \end{itemize} - \end{itemize} -\begin{lstlisting} -def foo(a=10, b=100): - print a, b -def func(*args, **keyword): - print args, keyword -# Unpacking: -args = [5, 10] -foo(*args) -kw = {'a':5, 'b':10} -foo(**kw) -\end{lstlisting} -\end{frame} - -\subsection{Modules, exceptions, classes} - -\begin{frame} - \frametitle{Modules} - \begin{itemize} - \item Define variables, functions and classes in a file with a - \typ{.py} extension - \item This file becomes a module! - \item Modules are searched in the following: - \begin{itemize} - \item Current directory - \item Standard: \typ{/usr/lib/python2.3/site-packages/} etc. - \item Directories specified in PYTHONPATH - \item \typ{sys.path}: current path settings (from the \typ{sys} - module) - \end{itemize} - \item The \typ{import} keyword ``loads'' a module - \item One can also use: - \mbox{\typ{from module import name1, name2, name2}}\\ - where \typ{name1} etc. are names in the module, ``module'' - \item \typ{from module import *} \ --- imports everything from module, - \alert{use only in interactive mode} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Modules: example} - \begin{lstlisting} -# --- foo.py --- -some_var = 1 -def fib(n): # write Fibonacci series up to n - """Print a Fibonacci series up to n.""" - a, b = 0, 1 - while b < n: - print b, - a, b = b, a+b -# EOF - ->>> import foo ->>> foo.fib(10) -1 1 2 3 5 8 ->>> foo.some_var -1 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Namespaces} - \begin{itemize} - \item A mapping from names to objects - \item Modules introduce a namespace - \item So do classes - \item The running script's namespace is \verb+__main__+ - \item A modules namespace is identified by its name - \item The standard functions (like \typ{len}) are in the - \verb+__builtin__+ namespace - \item Namespaces help organize different names and their bindings to - different objects - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Exceptions} - \begin{itemize} - \item Python's way of notifying you of errors - \item Several standard exceptions: \typ{SyntaxError}, \typ{IOError} - etc. - \item Users can also \typ{raise} errors - \item Users can create their own exceptions - \item Exceptions can be ``caught'' via \typ{try/except} blocks - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exception: examples} -\begin{lstlisting} ->>> 10 * (1/0) -Traceback (most recent call last): - File "", line 1, in ? -ZeroDivisionError: integer division or modulo by zero ->>> 4 + spam*3 -Traceback (most recent call last): - File "", line 1, in ? -NameError: name 'spam' is not defined ->>> '2' + 2 -Traceback (most recent call last): - File "", line 1, in ? -TypeError: cannot concatenate 'str' and 'int' objects -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exception: examples} -\begin{lstlisting} ->>> while True: -... try: -... x = int(raw_input("Enter a number: ")) -... break -... except ValueError: -... print "Invalid number, try again..." -... ->>> # To raise exceptions -... raise ValueError, "your error message" -Traceback (most recent call last): - File "", line 2, in ? -ValueError: your error message -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes: the big picture} - \begin{itemize} - \item Lets you create new data types - \item Class is a template for an object belonging to that class - \item Note: in Python a class is also an object - \item Instantiating a class creates an instance (an object) - \item An instance encapsulates the state (data) and behavior - (methods) - \item Allows you to define an inheritance hierarchy - \begin{itemize} - \item ``A Honda car \alert{is a} car.'' - \item ``A car \alert{is an} automobile.'' - \item ``A Python \alert{is a} reptile.'' - \end{itemize} - \item Programmers need to think OO - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes: what's the big deal?} - \begin{itemize} - \item Lets you create objects that mimic a real problem being - simulated - \item Makes problem solving more natural and elegant - \item Easier to create code - \item Allows for code-reuse - \item Polymorphism - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Class definition and instantiation} - \begin{itemize} - \item Class definitions when executed create class objects - \item Instantiating the class object creates an instance of the - class - \end{itemize} -\footnotesize -\begin{lstlisting} -class Foo(object): - pass -# class object created. -# Create an instance of Foo. -f = Foo() -# Can assign an attribute to the instance -f.a = 100 -print f.a -100 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes \ldots} - \begin{itemize} - \item All attributes are accessed via the \typ{object.attribute} - syntax - \item Both class and instance attributes are supported - \item \emph{Methods} represent the behavior of an object: crudely - think of them as functions ``belonging'' to the object - \item All methods in Python are ``virtual'' - \item Inheritance through subclassing - \item Multiple inheritance is supported - \item No special public and private attributes: only good - conventions - \begin{itemize} - \item \verb+object.public()+: public - \item \verb+object._private()+ \& \verb+object.__priv()+: - non-public - \end{itemize} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes: examples} -\begin{lstlisting} -class MyClass(object): - """Example class (this is the class docstring).""" - i = 12345 # A class attribute - def f(self): - """This is the method docstring""" - return 'hello world' - ->>> a = MyClass() # creates an instance ->>> a.f() -'hello world' ->>> # a.f() is equivalent to MyClass.f(a) -... # This also explains why f has a 'self' argument. -... MyClass.f(a) -'hello world' -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes (continued)} - \begin{itemize} - \item \typ{self} is \alert{conventionally} the first argument for a - method - \item In previous example, \typ{a.f} is a method object - \item When \typ{a.f} is called, it is passed the instance \typ{a} as - the first argument - \item If a method called \verb+__init__+ exists, it is called when - the object is created - \item If a method called \verb+__del__+ exists, it is called before - the object is garbage collected - \item Instance attributes are set by simply ``setting'' them in - \typ{self} - \item Other special methods (by convention) like \verb+__add__+ let - you define numeric types: - {\footnotesize \url{http://docs.python.org/ref/specialnames.html} - \\ \url{http://docs.python.org/ref/numeric-types.html} - } - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes: examples} -\begin{lstlisting} -class Bag(MyClass): # Shows how to derive classes - def __init__(self): # called on object creation. - self.data = [] # an instance attribute - def add(self, x): - self.data.append(x) - def addtwice(self, x): - self.add(x) - self.add(x) ->>> a = Bag() ->>> a.f() # Inherited method -'hello world' ->>> a.add(1); a.addtwice(2) ->>> a.data -[1, 2, 2] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Derived classes} - \begin{itemize} - \item Call the parent's \verb+__init__+ if needed - \item If you don't need a new constructor, no need to define it in subclass - \item Can also use the \verb+super+ built-in function - \end{itemize} -\begin{lstlisting} -class AnotherBag(Bag): - def __init__(self): - # Must call parent's __init__ explicitly - Bag.__init__(self) - # Alternatively use this: - super(AnotherBag, self).__init__() - # Now setup any more data. - self.more_data = [] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Classes: polymorphism} -\begin{lstlisting} -class Drawable(object): - def draw(self): - # Just a specification. - pass -\end{lstlisting} -\mode{\pause} -\begin{lstlisting} -class Square(Drawable): - def draw(self): - # draw a square. -class Circle(Drawable): - def draw(self): - # draw a circle. -\end{lstlisting} -\mode{\pause} -\begin{lstlisting} -class Artist(Drawable): - def draw(self): - for obj in self.drawables: - obj.draw() -\end{lstlisting} -\end{frame} - -\subsection{Miscellaneous} - -\begin{frame}[fragile] - \frametitle{Stand-alone scripts} -Consider a file \typ{f.py}: -\begin{lstlisting} -#!/usr/bin/env python -"""Module level documentation.""" -# First line tells the shell that it should use Python -# to interpret the code in the file. -def f(): - print "f" - -# Check if we are running standalone or as module. -# When imported, __name__ will not be '__main__' -if __name__ == '__main__': - # This is not executed when f.py is imported. - f() -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{List comprehensions} -\begin{lstlisting} ->>> veg = ['tomato', 'cabbage', 'carrot', 'potato'] ->>> [x.upper() for x in veg] -['TOMATO', 'CABBAGE', 'CARROT', 'POTATO'] ->>> vec = range(0, 8) ->>> even = [x for x in vec if x%2 == 0] ->>> even -[0, 2, 4, 6] ->>> [x*x for x in even] -[0, 4, 16, 36] ->>> odd = [x for x in vec if x%2 == 1] ->>> odd -[1, 3, 5, 7] ->>> [x*y for x in even for y in odd] -[0, 0, 0, 0, 2, 6, 10, 14, 4, 12, 20, 28, 6, 18,30,42] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{File handling} -\begin{lstlisting} ->>> # Reading files: -... f = open('/path/to/file_name') ->>> data = f.read() # Read entire file. ->>> line = f.readline() # Read one line. ->>> # Read entire file appending each line into a list -... lines = f.readlines() ->>> f.close() # close the file. ->>> # Writing files: -... f = open('/path/to/file_name', 'w') ->>> f.write('hello world\n') -\end{lstlisting} - \begin{itemize} - \item \typ{tell()}: returns int of current position - \item \typ{seek(pos)}: moves current position to specified byte - \item Call \typ{close()} when done using a file - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Math} - \begin{itemize} - \item \typ{math} module provides basic math routines for - floats - \item \typ{cmath} module provides math routies for complex - numbers - \item \typ{random}: provides pseudo-random number generators - for various distributions - \item These are always available and part of the standard library - \item More serious math is provided by the NumPy/SciPy modules -- - these are not standard and need to be installed separately - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Timing and profiling} - \begin{itemize} - \item Timing code: use the \typ{time} module - \item Read up on \typ{time.time()} and \typ{time.clock()} - \item \typ{timeit}: is a better way of doing timing - \item IPython has handy \typ{time} and \typ{timeit} macros (type - \typ{timeit?} for help) - \item IPython lets you debug and profile code via the \typ{run} - macro (type \typ{run?} on the prompt to learn more) - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Odds and ends} - \begin{itemize} - \item \typ{dir([object])} function: attributes of given object - \item \typ{type(object)}: returns type information - \item \typ{str(), repr()}: convert object to string representation - \item \typ{isinstance, issubclass} - \item \typ{assert} statements let you do debugging assertions in - code - \item \typ{csv} module: reading and writing CSV files - \item \typ{pickle}: lets you save and load Python objects - (\alert{serialization}) - \item \typ{sys.argv}: command line arguments - \item \typ{os.path}: common path manipulations - \item Check out the Python Library reference: - \url{http://docs.python.org/lib/lib.html} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Test driven development (TDD)} - \begin{itemize} - \item Why? - \begin{itemize} - - \item Forces you to write reusable code! - - \item Think about the API - - \item More robust - - \item Makes refactoring very easy - - \end{itemize} - \item How? Python offers three major ways of doing this - \begin{itemize} - \item doctest - \item unittest - \item nosetest (and similar like py.test) - \end{itemize} - - \item Test every piece of functionality you offer - - \item This isn't a formal introduction but more a practical one - - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Unit test} -\begin{lstlisting} -import unittest - -class MyTestCase(unittest.TestCase): - def setUp(self): - # Called *before* each test_* - def tearDown(self): - # Called *after* each test_* - def test_something(self): - "docstring" - # Test code. - self.assertEqual(x, y) - self.assertRaises(ValueError, func, arg1, arg2 ...) - -if __name__ == '__main__': - unittest.main() -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Nosetest} -\begin{lstlisting} -import particle -def test_particle(): - # Use asserts here. - p = particle.Particle(1.0) - assert p.property[0] == 1.0 - assert p.property[2] == 0.0 - -if __name__ == '__main__': - import nose - nose.main() -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Testing} - \begin{itemize} - \item More details: see library reference and search for nosetest - \end{itemize} -\end{frame} - -\section{Numerics \& Plotting} - -\subsection{NumPy Arrays} - -\subsection{Plotting: Matplotlib} - -\begin{frame} - \frametitle{About \texttt{matplotlib}} - \begin{itemize} - \item Easy to use, scriptable, ``Matlab-like'' 2D plotting - \item Publication quality figures and interactive capabilities - \item Plots, histograms, power spectra, bar charts, errorcharts, - scatterplots, etc. - \item Also does polar plots, maps, contours - \item Support for simple \TeX\ markup - \item Multiple output backends (images, EPS, SVG, wx, Agg, Tk, GTK) - \item Cross-platform: Linux, Win32, Mac OS X - \item Good idea to use via IPython: \typ{ipython -pylab} - \item From scripts use: \typ{import pylab} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{More information} - \begin{itemize} - \item More information here: \url{http://matplotlib.sf.net} - \item \url{http://matplotlib.sf.net/tutorial.html} - \item \url{http://matplotlib.sf.net/screenshots.html} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic plotting with \texttt{matplotlib}} -\begin{lstlisting} ->>> x = arange(0, 2*pi, 0.05) ->>> plot(x, sin(x)) # Same as plot(x, sin(x), 'b-') ->>> plot(x, sin(x), 'ro') ->>> axis([0,2*pi, -1,1]) ->>> xlabel(r'$\chi$', color='g') ->>> ylabel(r'sin($\chi$)', color='r') ->>> title('A simple figure', fontsize=20) ->>> savefig('/tmp/test.eps') -# Multiple plots in one figure ->>> t = arange(0.0, 5.2, 0.2) -# red dashes, blue squares and green triangles ->>> plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic plotting \ldots} -\begin{lstlisting} -# Set properties of objects: ->>> plot(x, sin(x), linewidth=2.0, color='r') ->>> l, = plot(x, sin(x)) ->>> setp(l, linewidth=2.0, color='r') ->>> l.set_linewidth(2.0); l.set_color('r') ->>> draw() # Redraws current figure. ->>> setp(l) # Prints available properties ->>> close() # Closes the figure. -# Multiple figures: ->>> figure(1); plot(x, sin(x)) ->>> figure(2); plot(x, tanh(x)) ->>> figure(1); title('Easy as 1,2,3') -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic plotting \ldots} -\begin{lstlisting} ->>> figure(1) ->>> subplot(211) # Same as subplot(2, 1, 1) ->>> plot(x, cos(5*x)*exp(-x)) ->>> subplot(2, 1, 2) ->>> plot(x, cos(5*x), 'r--', label='cosine') ->>> plot(x, sin(5*x), 'g--', label='sine') ->>> legend() # Or legend(['cosine', 'sine']) ->>> text(1,0, '(1,0)') ->>> axes = gca() # Current axis ->>> fig = gcf() # Current figure -\end{lstlisting} -\end{frame} - - -\subsection{SciPy} - -\begin{frame} - \frametitle{Using \texttt{SciPy}} - \begin{itemize} - \item SciPy is Open Source software for mathematics, science, and - engineering - \item \typ{import scipy} - \item Built on NumPy - \item Provides modules for statistics, optimization, integration, - linear algebra, Fourier transforms, signal and image processing, - genetic algorithms, ODE solvers, special functions, and more - \item Used widely by scientists world over - \item Details are beyond the scope of this tutorial - \end{itemize} -\end{frame} - -\section{Standard library} - -\subsection{Quick Tour} - -\begin{frame} - \frametitle{Standard library} - \begin{itemize} - \item Very powerful - \item ``Batteries included'' - \item Example standard modules taken from the tutorial - \begin{itemize} - \item Operating system interface: \typ{os} - \item System, Command line arguments: \typ{sys} - \item Regular expressions: \typ{re} - \item Math: \typ{math}, \typ{random} - \item Internet access: \typ{urllib2}, \typ{smtplib} - \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, - \typ{zipfile}, and \typ{tarfile} - \item Unit testing: \typ{doctest} and \typ{unittest} - \item And a whole lot more! - \end{itemize} - \item Check out the Python Library reference: - \url{http://docs.python.org/lib/lib.html} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Stdlib: examples} -\begin{lstlisting} ->>> import os ->>> os.system('date') -Fri Jun 10 22:13:09 IST 2005 -0 ->>> os.getcwd() -'/home/prabhu' ->>> os.chdir('/tmp') ->>> import os ->>> dir(os) - ->>> help(os) - -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Stdlib: examples} -\begin{lstlisting} ->>> import sys ->>> # Print the list of command line args to Python -... print sys.argv -[''] ->>> import re # Regular expressions ->>> re.findall(r'\bf[a-z]*', -... 'which foot or hand fell fastest') -['foot', 'fell', 'fastest'] ->>> re.sub(r'(\b[a-z]+) \1', r'\1', -... 'cat in the the hat') -'cat in the hat' -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Stdlib: examples} -\begin{lstlisting} ->>> import math ->>> math.cos(math.pi / 4.0) -0.70710678118654757 ->>> math.log(1024, 2) -10.0 ->>> import random ->>> random.choice(['apple', 'pear', 'banana']) -'pear' -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Stdlib: examples} -\begin{lstlisting} ->>> import urllib2 ->>> f = urllib2.urlopen('http://www.python.org/') ->>> print f.read(100) - ->> import zlib ->>> s = 'witch which has which witches wrist watch' ->>> len(s) -41 ->>> t = zlib.compress(s) ->>> len(t) -37 ->>> zlib.decompress(t) -'witch which has which witches wrist watch' ->>> zlib.crc32(t) --1438085031 -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Summary} - \begin{itemize} - \item Introduced Python - \item Basic syntax - \item Basic types and data structures - \item Control flow - \item Functions - \item Modules - \item Exceptions - \item Classes - \item Standard library - \end{itemize} -\end{frame} - -\end{document} - -\subsection{Basic data structures} -\begin{frame}{Lists} - \begin{itemize} - \item \texttt{species = [ 'humans', 'orcs', 'elves', 'dwarves' ]} - \item \texttt{ ids = [ 107, 109, 124, 141, 142, 144 ]} - \item \texttt{ oneliners = [ 'I will be back', 'Do or do not! No try!!', 42 ] } - \end{itemize} - - \begin{block}{List operations} - ids + [ 100, 102 ]\\ - species.append( 'unicorns')\\ - print oneliners[ 1 ]\\ - look up \alert{docs.python.org/tutorial/datastructures.html} - \end{block} -\end{frame} -\end{document} -\section{Python Tutorial} -\subsection{Preliminaries} -\begin{frame} - \frametitle{Using the interpreter} - \begin{itemize} - \item Starting up: \typ{python} or \typ{ipython} - \item Quitting: \typ{Control-D} or \typ{Control-Z} (on Win32) - \item Can use it like a calculator - \item Can execute one-liners via the \typ{-c} option: - \typ{python -c "print 'hello world'"} - \item Other options via \typ{python -h} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{IPython} - \begin{itemize} - \item Recommended interpreter, IPython: - \url{http://ipython.scipy.org} - \item Better than the default Python shell - \item Supports tab completion by default - \item Easier object introspection - \item Shell access! - \item Command system to allow extending its own behavior - \item Supports history (across sessions) and logging - \item Can be embedded in your own Python code - \item Support for macros - \item A flexible framework for your own custom interpreter - \item Other miscellaneous conveniences - \item We'll get back to this later - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic IPython features} - \begin{itemize} - \item Startup: \verb+ipython [options] files+ - \begin{itemize} - \item \verb+ipython [-wthread|-gthread|-qthread]+: - Threading modes to support wxPython, pyGTK and Qt - \item \verb+ipython -pylab+: Support for matplotlib - \end{itemize} - \item TAB completion: - \begin{itemize} - \item Type \verb+object_name.+ to see list of options - \item Also completes on file and directory names - \end{itemize} - \item \verb+object?+ shows docstring/help for any Python object - \item \verb+object??+ presents more docs (and source if possible) - \item Debugging with \verb+%pdb+ magic: pops up pdb on errors - \item Access history (saved over earlier sessions also) - \begin{itemize} - \item Use \texttt{}: move up history - \item Use \texttt{ string}: search history backwards - \item Use \texttt{Esc >}: get back to end of history - \end{itemize} - \item \verb+%run [options] file[.py]+ lets you run Python code - \end{itemize} -\end{frame} -% LocalWords: BDFL Guido Rossum PSF Nokia OO Zope CMS RedHat SciPy MayaVi spam -% LocalWords: IPython ipython stdin TypeError dict int elif PYTHONPATH IOError -% LocalWords: namespace Namespaces SyntaxError ZeroDivisionError NameError str -% LocalWords: ValueError subclassed def - - - \item Types are of two kinds: \alert{mutable} and \alert{immutable} - \item Immutable types: numbers, strings, \typ{None} and tuples - \item Immutables cannot be changed ``in-place'' - \item Mutable types: lists, dictionaries, instances, etc. - \item Mutable objects can be ``changed'' - \end{itemize} - - -\begin{frame} - \frametitle{Important!} - \begin{itemize} - \item Assignment to an object is by reference - \item Essentially, \alert{names are bound to objects} - \end{itemize} -\end{frame} - - -\end{document} -\begin{frame}[fragile] - \frametitle{Dictionaries} - \begin{itemize} - \item Associative arrays/mappings - \item Indexed by ``keys'' (keys must be immutable) - \item \typ{dict[key] = value} - \item \typ{keys()} returns all keys of the dict - \item \typ{values()} returns the values of the dict - \item \verb+has_key(key)+ returns if \typ{key} is in the dict - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Dictionaries: example} - \begin{lstlisting} ->>> tel = {'jack': 4098, 'sape': 4139} ->>> tel['guido'] = 4127 ->>> tel -{'sape': 4139, 'guido': 4127, 'jack': 4098} ->>> tel['jack'] -4098 ->>> del tel['sape'] ->>> tel['irv'] = 4127 ->>> tel -{'guido': 4127, 'irv': 4127, 'jack': 4098} ->>> tel.keys() -['guido', 'irv', 'jack'] ->>> tel.has_key('guido') -True - \end{lstlisting} -\end{frame} - -\subsection{Control flow, functions} - - - -\begin{frame}[fragile] - \frametitle{\typ{If} example} - \begin{lstlisting} ->>> a = ['cat', 'window', 'defenestrate'] ->>> if 'cat' in a: -... print "meaw" -... -meaw ->>> pets = {'cat': 1, 'dog':2, 'croc': 10} ->>> if 'croc' in pets: -... print pets['croc'] -... -10 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{for} example} - \begin{lstlisting} ->>> a = ['cat', 'window', 'defenestrate'] ->>> for x in a: -... print x, len(x) -... -cat 3 -window 6 -defenestrate 12 ->>> knights = {'gallahad': 'the pure', -... 'robin': 'the brave'} ->>> for k, v in knights.iteritems(): -... print k, v -... -gallahad the pure -robin the brave -\end{lstlisting} -\end{frame} diff -r ae070c133120 -r 24992ab48f2b day2/PythonMachinery.tex --- a/day2/PythonMachinery.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,325 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2008, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -%\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\texttt{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -%%% This is from Fernando's setup. -% \usepackage{color} -% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} -% % Use and configure listings package for nicely formatted code -% \usepackage{listings} -% \lstset{ -% language=Python, -% basicstyle=\small\ttfamily, -% commentstyle=\ttfamily\color{blue}, -% stringstyle=\ttfamily\color{orange}, -% showstringspaces=false, -% breaklines=true, -% postbreak = \space\dots -% } - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Python,\\a great programming toolkit:\\ -numerics and plotting} - -\author[Asokan \& Prabhu] {Asokan Pichai\\Prabhu Ramachandran} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {26, July 2009} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} -%\logo{\pgfuseimage{iitmlogo}} - - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each subsection: -\AtBeginSubsection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -% If you wish to uncover everything in a step-wise fashion, uncomment -% the following command: -%\beamerdefaultoverlayspecification{<+->} - -%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \frametitle{Outline} - \tableofcontents -\end{frame} -\section{Pythonicity} -\begin{frame}[fragile] - \frametitle{The Zen of Python} - -Try this! - -\begin{lstlisting} ->>> import this -\end{lstlisting} - -\end{frame} - -\begin{frame} - {Style Guide} - - Read PEP8 - - \url{http://www.python.org/dev/peps/pep-0008/} - - \inctime{10} -\end{frame} -\section{More Python Machinery} -\subsection{Objects} -\begin{frame}{Objects in Python} - \begin{itemize} - \item What is an Object? (Types and classes) - \item identity - \item type - \item method - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Why are they useful?} - \small - \begin{lstlisting} -for element in (1, 2, 3): - print element -for key in {'one':1, 'two':2}: - print key -for char in "123": - print char -for line in open("myfile.txt"): - print line -for line in urllib2.urlopen('http://site.com'): - print line - \end{lstlisting} -\end{frame} -\begin{frame}{And the winner is \ldots OBJECTS!} - All objects providing a similar inteface can be used the same way.\\ - Functions (and others) are first-class objects. Can be passed to and returned from functions. - \inctime{10} -\end{frame} -\subsection{Dictionary} -\begin{frame}{Dictionary} - \begin{itemize} - \item aka associative arrays, key-value pairs, hashmaps, hashtables \ldots - \item \typ{ d = \{ ``Hitchhiker's guide'' : 42, ``Terminator'' : ``I'll be back''\}} - \item lists and tuples index: 0 \ldots n - \item dictionaries index using strings - \item aka key-value pairs - \item what can be keys? - \end{itemize} -\end{frame} - -\begin{frame}{Dict \ldots } - \begin{itemize} - \item \alert{Unordered} - \begin{block}{Standard usage} - for key in dict:\\ - dict[key] \# => value - \end{block} - \item \typ{d.keys()} returns a list - \item can we have duplicate keys? - \end{itemize} -\end{frame} -\begin{frame} {Problem Set 2.1} - \begin{description} -\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. - \item[2.1.2] Count word frequencies in a file. - \item[2.1.3] Find the most used Python keywords in your Python code (import keyword). -\end{description} - -\inctime{20} -\end{frame} - -\subsection{Set} -\begin{frame}[fragile] - \frametitle{Set} - \begin{itemize} - \item Simplest container, mutable - \item No ordering, no duplicates - \item usual suspects: union, intersection, subset \ldots - \item >, >=, <, <=, in, \ldots - \end{itemize} - \begin{lstlisting} -f10 = set([1,2,3,5,8]) -p10 = set([2,3,5,7]) -f10|p10, f10&p10 -f10-p10, p10-f10, f10^p10 -set([2,3]) < p10, set([2,3]) <= p10 -2 in p10, 4 in p10 -len(f10) -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Problem set 2.2} - \begin{description} - \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? - \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. -\end{description} -\inctime{15} -\end{frame} - -\subsection{Functions Reloaded!} -\begin{frame}[fragile] - \frametitle{Advanced functions} - \begin{itemize} - \item default args - \item varargs - \item keyword args - \item scope - \item \typ{global} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Functions: default arguments} - \begin{lstlisting} -def ask_ok(prompt, retries=4, complaint='Yes or no!'): - while True: - ok = raw_input(prompt) - if ok in ('y', 'ye', 'yes'): - return True - if ok in ('n', 'no', 'nop', 'nope'): - return False - retries = retries - 1 - if retries < 0: - raise IOError, 'bad user' - print complaint - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Functions: keyword arguments} - \small - \begin{lstlisting} -def parrot(voltage, state='a stiff', - action='voom', type='Royal Blue'): - print "-- This parrot wouldn't", action, - print "if you supply", voltage, "Volts." - print "-- Lovely plumage, the", type - print "-- It's", state, "!" - -parrot(1000) -parrot(action = 'VOOOOOM', voltage = 1000000) -parrot('a thousand', state = 'pushing up the daisies') -parrot('a million', 'bereft of life', 'jump') -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Functions: arbitrary argument lists} - \begin{itemize} - \item Arbitrary number of arguments using \verb+*args+ or - \verb+*whatever+ - \item Keyword arguments using \verb+**kw+ - \item Given a tuple/dict how do you call a function? - \begin{itemize} - \item Using argument unpacking - \item For positional arguments: \verb+foo(*[5, 10])+ - \item For keyword args: \verb+foo(**{'a':5, 'b':10})+ - \end{itemize} - \end{itemize} -\end{frame} - - \begin{frame}[fragile] -\begin{lstlisting} -def foo(a=10, b=100): - print a, b -def func(*args, **keyword): - print args, keyword -# Unpacking: -args = [5, 10] -foo(*args) -kw = {'a':5, 'b':10} -foo(**kw) -\end{lstlisting} - \inctime{15} -\end{frame} - -\subsection{Functional programming} -\begin{frame}[fragile] - \frametitle{Functional programming} -What is the basic idea?\\ -Why is it interesting?\\ -\typ{map, reduce, filter}\\ -list comprehension\\ -generators - \inctime{10} -\end{frame} -\end{document} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff -r ae070c133120 -r 24992ab48f2b day2/session1.tex --- a/day2/session1.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,832 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -%\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -%%% This is from Fernando's setup. -% \usepackage{color} -% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} -% % Use and configure listings package for nicely formatted code -% \usepackage{listings} -% \lstset{ -% language=Python, -% basicstyle=\small\ttfamily, -% commentstyle=\ttfamily\color{blue}, -% stringstyle=\ttfamily\color{orange}, -% showstringspaces=false, -% breaklines=true, -% postbreak = \space\dots -% } - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[]{Arrays\\ \& \\2D Plotting} - -\author[FOSSEE Team] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {11, October 2009} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} -%\logo{\pgfuseimage{iitmlogo}} - - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each subsection: -\AtBeginSubsection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -\newcommand{\num}{\texttt{numpy}} - - -% If you wish to uncover everything in a step-wise fashion, uncomment -% the following command: -%\beamerdefaultoverlayspecification{<+->} - -%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \maketitle -\end{frame} - -\begin{frame} - \frametitle{Outline} - \tableofcontents - % You might wish to add the option [pausesections] -\end{frame} - -\section{Arrays} - -\subsection{Basic \typ{numpy}} - -\begin{frame} - \frametitle{The \num\ module} - \begin{itemize} - \item Why? - \item What: - \begin{itemize} - \item An efficient and powerful array type for various common data types - \item Abstracts out the most commonly used standard operations on arrays - \end{itemize} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Examples of \num} -\begin{lstlisting} -# Simple array math example ->>> from numpy import * ->>> a = array([1,2,3,4]) ->>> b = arange(2,6) ->>> b -array([2,3,4,5]) ->>> a*2 + b + 1 # Basic math! -array([5, 8, 11, 14]) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Examples of \num} -\begin{lstlisting} -# Pi and e are defined. ->>> x = linspace(0.0, 10.0, 1000) ->>> x *= 2*pi/10 # inplace. -# apply functions to array. ->>> y = sin(x) ->>> z = exp(y) -\end{lstlisting} -\inctime{5} -\end{frame} - -\begin{frame}[fragile] - \frametitle{More examples of \num} -\vspace*{-8pt} -\begin{lstlisting} ->>> x = array([1., 2, 3, 4]) ->>> size(x) -4 ->>> x.dtype # What is a.dtype? -dtype('float64') ->>> x.shape -(4,) ->>> print x.itemsize -8 ->>> x[0] = 10 ->>> print x[0], x[-1] -10.0 4.0 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Multi-dimensional arrays} -\begin{lstlisting} ->>> a = array([[ 0, 1, 2, 3], -... [10,11,12,13]]) ->>> a.shape # (rows, columns) -(2, 4) ->>> a.shape=4,2 -# Accessing and setting values ->>> a[1][3] ->>> a[1,3] ->>> a[1,3] = -1 ->>> a[1] # The second row -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Array math} - \begin{itemize} - \item Basic \alert{elementwise} math (given two arrays \typ{a, b}): - \typ{+, -, *, /, \%} - \item Inplace operators: \typ{a += b} - \item \typ{sum(x, axis=0)}, - \typ{product(x, axis=0)}, - \typ{dot(a, bp)} - \end{itemize} -\begin{lstlisting} ->>> x = array([[0,2,4,2],[1,2,3,4]]) ->>> sum(x) ->>> sum(x,axis=1) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Array math cont.} - \begin{itemize} - \item Logical operations: \typ{==}, \typ{!=}, - \typ{<}, \typ{>} etc. - \item Trig and other functions: \typ{sin(x),} - \typ{arcsin(x), sinh(x),} - \typ{exp(x), sqrt(x)} etc. - \end{itemize} -\begin{lstlisting} ->>> a<4, a!=3 ->>> sqrt(a) -\end{lstlisting} -\inctime{10} -\end{frame} - -\begin{frame} - \frametitle{Summary of Concepts} - \begin{itemize} - \item fixed size (\typ{arr.size}); - \item Same type (\typ{arr.dtype}) of data - \item arbitrary dimensionality - \item \typ{arr.shape}: size in each dimension - \item \alert{Note:} \typ{len(arr) != arr.size} in general - \item \alert{Note:} By default array operations are performed - \alert{elementwise} - \end{itemize} -\end{frame} - -\subsection{Array Creation \& Slicing, Striding Arrays} - -\begin{frame}[fragile] - \frametitle{Array creation functions} - \begin{itemize} - \item \typ{array?} \alert{\#Doc string reading} - \item \typ{array(object,dtype=None,...)} - \begin{lstlisting} ->>> array([2,3,4]) -array([2, 3, 4]) - \end{lstlisting} - \item \typ{linspace(start,stop,num)} - \begin{lstlisting} ->>> linspace(0, 2, 4) -array([0.,0.6666667,1.3333333,2.]) - \end{lstlisting} - \item \typ{arange?} - \alert{\# float version of range} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Array creation functions cont.} - \begin{itemize} - \item \typ{ones(shape, dtype=None, ...)} - \begin{lstlisting} ->>> ones((2,2)) -array([[ 1., 1.], - [ 1., 1.]]) - \end{lstlisting} - \item \typ{identity(n)} - \item \typ{ones\_like(x)} - \begin{lstlisting} ->>> a = array([[1,2,3],[4,5,6]]) ->>> ones_like(a) -array([[1, 1, 1], - [1, 1, 1]]) - \end{lstlisting} - \item Also try \typ{zeros, zeros\_like, empty} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Slicing arrays} -\begin{lstlisting} ->>> a = array([[1,2,3], [4,5,6], - [7,8,9]]) ->>> a[0,1:3] -array([2, 3]) ->>> a[1:,1:] -array([[5, 6], - [8, 9]]) ->>> a[:,2] -array([3, 6, 9]) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Striding arrays} -\begin{lstlisting} ->>> a[0::2,0::2] -array([[1, 3], - [7, 9]]) -# Slices are references to the -# same memory! -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] -\frametitle{Random Numbers} -\begin{lstlisting} ->>> random.random() -0.94134734326214331 ->>> random.random(2) -array([ 0.73955352, 0.49463645]) ->>> random.random(3,2) -array([[ 0.96276665, 0.77174861], - [ 0.35138557, 0.61462271], - [ 0.16789255, 0.43848811]]) -\end{lstlisting} -\inctime{15} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problem} - Finite difference - \begin{equation*} - \frac{sin(x+h)-sin(x)}{h} - \end{equation*} - \begin{lstlisting} - >>> x = linspace(0,2*pi,100) - >>> y = sin(x) - >>> deltax = x[1]-x[0] - \end{lstlisting} - \pause - \begin{enumerate} - \item Given this, get the finite difference of sin in the range 0 to 2*pi - \end{enumerate} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Advanced Problem} - \begin{lstlisting} - >>> from scipy import misc - >>> A=misc.imread('filename') - >>> misc.imshow(A) - \end{lstlisting} - \begin{enumerate} - \item Convert an RGB image to Grayscale. $ Y = 0.5R + 0.25G + 0.25B $ - \item Scale the image to 50\% - \item Introduce some random noise - \item Smooth the image using a mean filter - \\\small{Each element in the array is replaced by mean of all the neighbouring elements} - \\\small{How fast does your code run?} - \end{enumerate} -\inctime{15} -\end{frame} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\section{2D Plotting} -\subsection{Getting Started} - -\begin{frame} - {IPython's \typ{pylab} mode} -\begin{block}{Immediate use -} - \typ{\$ ipython -pylab} -\end{block} -\begin{itemize} - \item \typ{pylab}: convenient 2D plotting interface to MPL - \item Imports all of pylab for you! - \item Allows for interactive plotting -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Basic 2D plotting} - -\begin{lstlisting} ->>> x = linspace(0, 2*pi, 1000) ->>> plot(x, sin(x)) ->>> plot(x, sin(x), 'ro') ->>> xlabel(r'$\chi$', color='g') -# LaTeX markup! ->>> ylabel(r'sin($\chi$)', color='r') ->>> title('Simple figure', fontsize=20) ->>> savefig('/tmp/test.png') -\end{lstlisting} -\begin{itemize} - \item Also: PS, EPS, SVG, PDF -\end{itemize} -\inctime{5} -\end{frame} - -\subsection{Plots - Lines, Labels and Legends} -\begin{frame}[fragile] - \frametitle{Tweaking plots} -\begin{lstlisting} -# Set properties of objects: ->>> l, = plot(x, sin(x)) -# Why "l,"? ->>> setp(l, linewidth=2.0, color='r') ->>> l.set_linewidth(2.0) ->>> draw() # Redraw. ->>> setp(l) # Print properties. ->>> clf() # Clear figure. ->>> close() # Close figure. -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Working with text \ldots} -%\begin{itemize} -% \item We already saw LaTeX markup support! -%\end{itemize} -\begin{lstlisting} ->>> w = arange(-2,2,.1) ->>> plot(w,exp(-(w*w))*cos) ->>> ylabel('$f(\omega)$') ->>> xlabel('$\omega$') ->>> title(r"$f(\omega)=e^{-\omega^2} - cos({\omega^2})$") -\end{lstlisting} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Legends} -\begin{lstlisting} ->>> x = linspace(0, 2*pi, 1000) ->>> plot(x, cos(5*x), 'r--', - label='cosine') ->>> plot(x, sin(5*x), 'g--', - label='sine') ->>> legend() -# Or use: ->>> legend(['cosine', 'sine']) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Multiple figures} - -\begin{lstlisting} ->>> figure(1) ->>> plot(x, sin(x)) ->>> figure(2) ->>> plot(x, tanh(x)) ->>> figure(1) ->>> title('Easy as 1,2,3') -\end{lstlisting} - - -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{pylab} in Python scripts} -\begin{lstlisting} -import pylab -x = pylab.linspace(0, 20, 1000) -pylab.plot(x, pylab.sin(x)) - -# Can also use: -from pylab import linspace, sin, plot -\end{lstlisting} -\inctime{10} -\end{frame} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -\subsection{Types of Plots} -\begin{frame}[fragile] - \frametitle{X-Y plot} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/xyplot} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -t1 = arange(0.0, 5.0, 0.1) -t2 = arange(0.0, 5.0, 0.02) -t3 = arange(0.0, 2.0, 0.01) -subplot(211) -plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', - t2, cos(2*pi*t2)*exp(-t2), 'k') -grid(True) -title('A tale of 2 subplots') -ylabel('Damped') -subplot(212) -plot(t3, cos(2*pi*t3), 'r--') -grid(True) -xlabel('time (s)') -ylabel('Undamped') -\end{lstlisting} - \end{block} - \end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Semi-log and log-log plots} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/log} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -dt = 0.01 -t = arange(dt, 20.0, dt) -subplot(311) -semilogy(t, exp(-t/5.0)) -ylabel('semilogy') -grid(True) -subplot(312) -semilogx(t, sin(2*pi*t)) -ylabel('semilogx') -grid(True) -# minor grid on too -gca().xaxis.grid(True, which='minor') -subplot(313) -loglog(t, 20*exp(-t/10.0), basex=4) -grid(True) -ylabel('loglog base 4 on x') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Errorbar} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/errorbar} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -t = arange(0.1, 4, 0.1) -s = exp(-t) -e = 0.1*abs(randn(len(s))) -f = 0.1*abs(randn(len(s))) -g = 2*e -h = 2*f -errorbar(t, s, [e,g], f, fmt='o') -xlabel('Distance (m)') -ylabel('Height (m)') -title('Mean and standard error '\ - 'as a function of distance') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Histogram} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/histogram} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -mu, sigma = 100, 15 -x = mu + sigma*randn(10000) -# the histogram of the data -n, bins, patches = hist(x, 100, normed=1) -# add a 'best fit' line -y = normpdf( bins, mu, sigma) -l = plot(bins, y, 'r--', linewidth=2) -xlim(40, 160) -xlabel('Smarts') -ylabel('P') -title(r'$\rm{IQ:}\/ \mu=100,\/ \sigma=15$') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Bar charts} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/barchart} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -N = 5 -menMeans = (20, 35, 30, 35, 27) -menStd = ( 2, 3, 4, 1, 2) -# the x locations for the groups -ind = arange(N) -# the width of the bars -width = 0.35 -p1 = bar(ind, menMeans, width, - color='r', yerr=menStd) -womenMeans = (25, 32, 34, 20, 25) -womenStd = ( 3, 5, 2, 3, 3) -p2 = bar(ind+width, womenMeans, width, - color='y', yerr=womenStd) -ylabel('Scores') -title('Scores by group and gender') -xticks(ind+width, - ('G1', 'G2', 'G3', 'G4', 'G5')) -xlim(-width,len(ind)) -yticks(arange(0,41,10)) -legend((p1[0], p2[0]), - ('Men', 'Women'), shadow=True) -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Pie charts} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.4in} - \includegraphics[height=2.0in, interpolate=true]{data/piechart} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -# make a square figure and axes -figure(1, figsize=(8,8)) -ax = axes([0.1, 0.1, 0.8, 0.8]) -labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' -fracs = [15,30,45, 10] -explode=(0, 0.05, 0, 0) -pie(fracs, explode=explode, labels=labels, - autopct='%1.1f%%', shadow=True) -title('Raining Hogs and Dogs', - bbox={'facecolor':'0.8', 'pad':5}) -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Scatter plots} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.4in} - \includegraphics[height=2in, interpolate=true]{data/scatter} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -N = 30 -x = 0.9*rand(N) -y = 0.9*rand(N) -# 0 to 10 point radiuses -area = pi*(10 * rand(N))**2 -volume = 400 + rand(N)*450 -scatter(x,y,s=area, marker='o', c=volume, - alpha=0.75) -xlabel(r'$\Delta_i$', size='x-large') -ylabel(r'$\Delta_{i+1}$', size='x-large') -title(r'Volume and percent change') -grid(True) -colorbar() -savefig('scatter') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Polar} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/polar} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -figure(figsize=(8,8)) -ax = axes([0.1, 0.1, 0.8, 0.8], - polar=True, - axisbg='#d5de9c') -r = arange(0,1,0.001) -theta = 2*2*pi*r -polar(theta, r, color='#ee8d18', lw=3) -# the radius of the grid labels -setp(ax.thetagridlabels, y=1.075) -title(r'$\theta=4\pi r$', fontsize=20) -\end{lstlisting} - - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Contours} - \begin{columns} - \column{0.45\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/contour} - \column{0.525\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -x = arange(-3.0, 3.0, 0.025) -y = arange(-2.0, 2.0, 0.025) -X, Y = meshgrid(x, y) -Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) -Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) -# difference of Gaussians -Z = 10.0 * (Z2 - Z1) -im = imshow(Z, interpolation='bilinear', - origin='lower', - cmap=cm.gray, extent=(-3,3,-2,2)) -levels = arange(-1.2, 1.6, 0.2) -# label every second level -clabel(CS, levels[1::2], inline=1, - fmt='%1.1f', fontsize=14) -CS = contour(Z, levels, - origin='lower', - linewidths=2, - extent=(-3,3,-2,2)) -# make a colorbar for the contour lines -CB = colorbar(CS, shrink=0.8, extend='both') -title('Lines with colorbar') -hot(); flag() -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Velocity vectors} - \begin{columns} - \column{0.5\textwidth} - \hspace*{-0.5in} - \includegraphics[height=2in, interpolate=true]{data/quiver} - \column{0.45\textwidth} - \begin{block}{Example code} - \tiny -\begin{lstlisting} -X,Y = meshgrid(arange(0,2*pi,.2), - arange(0,2*pi,.2) ) -U = cos(X) -V = sin(Y) -Q = quiver(X[::3, ::3], Y[::3, ::3], - U[::3, ::3], V[::3, ::3], - color='r', units='x', - linewidths=(2,), - edgecolors=('k'), - headaxislength=5 ) -qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', - fontproperties= - {'weight': 'bold'}) -axis([-1, 7, -1, 7]) -title('triangular head; scale '\ - 'with x view; black edges') -\end{lstlisting} - \end{block} -\end{columns} -\end{frame} - -\begin{frame}[fragile] \frametitle{Maps} - \includegraphics[height=2.3in, interpolate=true]{data/plotmap} - \begin{center} - \tiny - For details see \url{http://matplotlib.sourceforge.net/screenshots/plotmap.py} - \end{center} -\end{frame} - - -\begin{frame} - \frametitle{More information} - \begin{itemize} - \item More information here: \url{http://matplotlib.sf.net} - \item \url{http://matplotlib.sf.net/tutorial.html} - \item \url{http://matplotlib.sf.net/screenshots.html} - \end{itemize} -\inctime{5} -\end{frame} - -\begin{frame} - \frametitle{Problem Set} - \begin{itemize} - \item[1] Write a function that plots any regular n-gon given \typ{n}. - \item[2] Consider the logistic map, $f(x) = kx(1-x)$, plot it for - $k=2.5, 3.5$ and $4$ in the same plot. -\end{itemize} -\end{frame} - -\begin{frame}[fragile] -\frametitle{Problem Set} - \begin{columns} - \column{0.6\textwidth} - \small{ - \begin{itemize} - \item[3] Consider the iteration $x_{n+1} = f(x_n)$ where $f(x) = kx(1-x)$. Plot the successive iterates of this process as explained below. - \end{itemize}} - \column{0.35\textwidth} - \hspace*{-0.5in} - \includegraphics[height=1.6in, interpolate=true]{data/cobweb} -\end{columns} -\end{frame} - -\begin{frame} - - Plot the cobweb plot as follows: - \begin{enumerate} - \item Start at $(x_0, 0)$ ($\implies$ i=0) - \item Draw a line to $(x_i, f(x_i))$ - \item Set $x_{i+1} = f(x_i)$ - \item Draw a line to $(x_{i+1}, x_{i+1})$ - \item $(i\implies i+1)$ - \item Repeat from 2 for as long as you want - \end{enumerate} -\inctime{20} -\end{frame} - -\begin{frame}{Summary} - \begin{itemize} - \item Basics of Numpy. - \item Array operations. - \item Plotting in 2D. - \end{itemize} -\end{frame} -\end{document} diff -r ae070c133120 -r 24992ab48f2b day2/session2.tex --- a/day2/session2.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,431 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -%\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -%%% This is from Fernando's setup. -% \usepackage{color} -% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} -% % Use and configure listings package for nicely formatted code -% \usepackage{listings} -% \lstset{ -% language=Python, -% basicstyle=\small\ttfamily, -% commentstyle=\ttfamily\color{blue}, -% stringstyle=\ttfamily\color{orange}, -% showstringspaces=false, -% breaklines=true, -% postbreak = \space\dots -% } - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[]{Numerical Computing with Numpy \& Scipy} - -\author[FOSSEE Team] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {11, October 2009} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} -%\logo{\pgfuseimage{iitmlogo}} - - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each subsection: -\AtBeginSubsection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -% If you wish to uncover everything in a step-wise fashion, uncomment -% the following command: -%\beamerdefaultoverlayspecification{<+->} - -%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \maketitle -\end{frame} - -\section{Advanced Numpy} -\begin{frame}[fragile] - \frametitle{Broadcasting} - \begin{lstlisting} - >>> a = arange(4) - >>> b = arange(5) - >>> a+b #Does this work? - >>> a+3 - >>> c = array([3]) - >>> a+c #Works! - >>> b+c #But how? - >>> a.shape, b.shape, c.shape - \end{lstlisting} - \begin{itemize} - \item Enter Broadcasting! - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Broadcasting} - \begin{columns} - \column{0.65\textwidth} - \hspace*{-1.5in} - \begin{lstlisting} - >>> a = arange(4) - >>> a+3 - array([3, 4, 5, 6]) - \end{lstlisting} - \column{0.35\textwidth} - \includegraphics[height=0.7in, interpolate=true]{data/broadcast_scalar} - \end{columns} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Broadcasting in 3D} - \begin{lstlisting} - >>> x = ones((3, 5, 1)) - >>> y = ones(8) - >>> (x + y).shape - (3, 5, 8) - \end{lstlisting} - \begin{figure} - \begin{center} - \includegraphics[height=1.5in, interpolate=true]{data/array_3x5x8} - \end{center} - \end{figure} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Copies \& Views} - \vspace{-0.1in} - \begin{lstlisting} - >>> a = arange(1,9); a.shape=3,3 - >>> b = a - >>> b is a - >>> b[0,0]=0; print a - >>> c = a.view() - >>> c is a - >>> c.base is a - >>> c.flags.owndata - >>> d = a.copy() - >>> d.base is a - >>> d.flags.owndata - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Copies \& Views} - \vspace{-0.1in} - \begin{lstlisting} - >>> b = a[0,1:3] - >>> c = a[0::2,0::2] - >>> a.flags.owndata - >>> b.flags.owndata - >>> b.base - >>> c.base is a - \end{lstlisting} - \begin{itemize} - \item Slicing and Striding just reference the same memory - \item They produce views of the data, not copies - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Copies contd \ldots} - \begin{lstlisting} - >>> a = arange(1, 10, 2) - >>> b = a[array([0,2,3])] - >>> b.flags.owndata - >>> abool=a>5 - >>> c = a[abool] - >>> c.flags.owndata - \end{lstlisting} - \begin{itemize} - \item Indexing arrays or Boolean arrays produce copies - \end{itemize} -\inctime{15} -\end{frame} - -\section{SciPy} -\subsection{Introduction} -\begin{frame} - {Intro to SciPy} - \begin{itemize} - \item \url{http://www.scipy.org} - \item Open source scientific libraries for Python - \item Based on NumPy - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{SciPy} - \begin{itemize} - \item Provides: - \begin{itemize} - \item Linear algebra - \item Numerical integration - \item Fourier transforms - \item Signal processing - \item Special functions - \item Statistics - \item Optimization - \item Image processing - \item ODE solvers - \end{itemize} - \item Uses LAPACK, QUADPACK, ODEPACK, FFTPACK etc. from netlib - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{SciPy - Functions \& Submodules} - \begin{itemize} - \item All \typ{numpy} functions are in \typ{scipy} namespace - \item Domain specific functions organized into subpackages - \item Subpackages need to be imported separately - \end{itemize} - \begin{lstlisting} - >>> from scipy import linalg - \end{lstlisting} -\end{frame} - -\subsection{Linear Algebra} -\begin{frame}[fragile] - \frametitle{Linear Algebra} - \begin{lstlisting} - >>> import scipy as sp - >>> from scipy import linalg - >>> A = sp.array(sp.arange(1,10)) - >>> A.shape = 3,3 - >>> linalg.inv(A) - >>> linalg.det(A) - >>> linalg.norm(A) - >>> linalg.expm(A) #logm - >>> linalg.sinm(A) #cosm, tanm, ... - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Linear Algebra ...} - \begin{lstlisting} - >>> A = sp.array(sp.arange(1,10)) - >>> A.shape = 3,3 - >>> linalg.lu(A) - >>> linalg.eig(A) - >>> linalg.eigvals(A) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Solving Linear Equations} - \vspace{-0.2in} - \begin{align*} - 3x + 2y - z & = 1 \\ - 2x - 2y + 4z & = -2 \\ - -x + \frac{1}{2}y -z & = 0 - \end{align*} - To Solve this, - \begin{lstlisting} - >>> A = sp.array([[3,2,-1],[2,-2,4] - ,[-1,1/2,-1]]) - >>> b = sp.array([1,-2,0]) - >>> x = linalg.solve(A,b) - >>> Ax = sp.dot(A,x) - >>> sp.allclose(Ax, b) - \end{lstlisting} -\inctime{15} -\end{frame} - -\subsection{Integration} -\begin{frame}[fragile] - \frametitle{Integrate} - \begin{itemize} - \item Integrating Functions given function object - \item Integrating Functions given fixed samples - \item Numerical integrators of ODE systems - \end{itemize} - Calculate the area under $(sin(x) + x^2)$ in the range $(0,1)$ - \begin{lstlisting} - >>> def f(x): - return sin(x)+x**2 - >>> integrate.quad(f, 0, 1) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Integrate \ldots} - Numerically solve ODEs\\ - \begin{align*} - \frac{dx}{dt}&=-e^{-t}x^2\\ - x&=2 \quad at \ t=0 - \end{align*} - \begin{lstlisting} ->>> def dx_dt(x,t): - return -exp(-t)*x**2 ->>> t = linspace(0,2,100) ->>> x = integrate.odeint(dx_dt, 2, t) ->>> plt.plot(x,t) - \end{lstlisting} -\inctime{10} -\end{frame} - -\subsection{Interpolation} -\begin{frame}[fragile] - \frametitle{Interpolation} - \begin{lstlisting} ->>> from scipy import interpolate ->>> interpolate.interp1d? ->>> x = arange(0,2*pi,pi/4) ->>> y = sin(x) ->>> fl = interpolate.interp1d( - x,y,kind='linear') ->>> fc = interpolate.interp1d( - x,y,kind='cubic') ->>> fl(pi/3) ->>> fc(pi/3) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Interpolation - Splines} - Plot the Cubic Spline of $sin(x)$ - \begin{lstlisting} ->>> tck = interpolate.splrep(x,y) ->>> xs = arange(0,2*pi,pi/50) ->>> ys = interpolate.splev(X,tck,der=0) ->>> plt.plot(x,y,'o',x,y,xs,ys) ->>> plt.show() - \end{lstlisting} -\inctime{10} -\end{frame} - -\subsection{Signal Processing} -\begin{frame}[fragile] - \frametitle{Signal \& Image Processing} - \begin{itemize} - \item Convolution - \item Filtering - \item Filter design - \item IIR filter design - \item Linear Systems - \item LTI Representations - \item Window functions - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Signal \& Image Processing} - Applying a simple median filter - \begin{lstlisting} ->>> from scipy import signal, ndimage ->>> from scipy import lena ->>> A = lena().astype('float32') ->>> B = signal.medfilt2d(A) ->>> imshow(B) - \end{lstlisting} - Zooming an array - uses spline interpolation - \begin{lstlisting} ->>> b = ndimage.zoom(A,0.5) ->>> imshow(b) ->>> b = ndimage.zoom(A,2) - \end{lstlisting} - \inctime{5} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Problems} - The Van der Pol oscillator is a type of nonconservative oscillator with nonlinear damping. It evolves in time according to the second order differential equation: - \begin{equation*} - \frac{d^2x}{dt^2}+\mu(x^2-1)\frac{dx}{dt}+x= 0 - \end{equation*} - Make a plot of $\frac{dx}{dt}$ vs. $x$. -\inctime{30} -\end{frame} -\begin{frame}{Summary} - \begin{itemize} - \item Advanced NumPy - \item SciPy - \begin{itemize} - \item Linear Algebra - \item Integration - \item Interpolation - \item Signal and Image processing - \end{itemize} - \end{itemize} -\end{frame} -\end{document} - -- Numpy arrays (30 mins) - - Matrices - - random number generation. - - Image manipulation: jigsaw puzzle. - - Monte-carlo integration. diff -r ae070c133120 -r 24992ab48f2b day2/session3.tex --- a/day2/session3.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,498 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[compress,14pt]{beamer} -% \documentclass[handout]{beamer} -% \usepackage{pgfpages} -% \pgfpagesuselayout{4 on 1}[a4paper,border, shrink=5mm,landscape] -\usepackage{tikz} -\newcommand{\hyperlinkmovie}{} -%\usepackage{movie15} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Note that in presentation mode -% \paperwidth 364.19536pt -% \paperheight 273.14662pt -% h/w = 0.888 - - -\mode -{ - \usetheme{Warsaw} - %\usetheme{Boadilla} - %\usetheme{default} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -% To remove navigation symbols -\setbeamertemplate{navigation symbols}{} - -\usepackage{amsmath} -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} -\usepackage{pgf} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% My Macros -\setbeamercolor{postit}{bg=yellow,fg=black} -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -%{\centerline{\fcolorbox{gray!50} {blue!10}{ -%\begin{minipage}{0.9\linewidth} -% {#1} -%\end{minipage} -% }}} - -\newcommand{\myemph}[1]{\structure{\emph{#1}}} -\newcommand{\PythonCode}[1]{\lstinline{#1}} - -\newcommand{\tvtk}{\texttt{tvtk}} -\newcommand{\mlab}{\texttt{mlab}} - -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\vspace*{0.1in}\tiny \thetime\ m}} - -\newcommand\BackgroundPicture[1]{% - \setbeamertemplate{background}{% - \parbox[c][\paperheight]{\paperwidth}{% - \vfill \hfill - \hfill \vfill -}}} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Configuring the theme -%\setbeamercolor{normal text}{fg=white} -%\setbeamercolor{background canvas}{bg=black} - - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[]{3D data Visualization} - -\author[FOSSEE Team] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[]{11, October 2009} -%\date[] % (optional) - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitblogo}{iitblogo} -%\logo{\pgfuseimage{iitblogo}} - -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each subsection: -\AtBeginSubsection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \maketitle -\end{frame} - -\begin{frame} - \frametitle{Outline} - \tableofcontents - % You might wish to add the option [pausesections] -\end{frame} - -\section{3D Data Visualization} - -\begin{frame} - \frametitle{What is visualization?} - \Large - \begin{center} - Visual representation of data - \end{center} -\end{frame} - -\begin{frame} - \frametitle{3D visualization} - \Large - \begin{center} - Harder but important - \end{center} -\end{frame} - -\begin{frame} - \frametitle{Is this Graphics?} - \Large - \begin{center} - Visualization is about data! - \end{center} -\end{frame} - -\begin{frame} - \frametitle{Examples: trajectory in space} - \Large - \begin{center} - \pgfimage[width=2.5in]{MEDIA/m2/mlab/plot3d_ex} - \end{center} -\end{frame} - -\begin{frame} - \frametitle{Examples: Fire in a room} - \Large - \begin{center} - Demo of data - \end{center} -\inctime{10} -\end{frame} - -\section{Tools at your disposal} - -\subsection{Mayavi2} - -\begin{frame} - \frametitle{Introduction to Mayavi} - \begin{itemize} - \item Most scientists not interested in details of visualization - \item Visualization of data files with a nice UI - \item Interactive visualization of data (think Matlab) - \item Embedding visualizations in applications - \item Customization - \end{itemize} - \pause - \begin{block}{The Goal} - Provide a \alert{flexible} library/app for every one of these needs! - \end{block} -\end{frame} - -\begin{frame} - {Overview of features} - \vspace*{-0.3in} - \begin{center} - \hspace*{-0.2in}\pgfimage[width=5in]{MEDIA/m2/m2_app3_3} - \end{center} -\end{frame} - - -\begin{frame} - \frametitle{Mayavi in applications} - \vspace*{-0.3in} - \begin{center} - \hspace*{-0.2in}\pgfimage[width=4.5in]{MEDIA/m2/m2_envisage} - \end{center} -\end{frame} - -\begin{frame} - \frametitle{Live in your dialogs} - \vspace*{0.1in} - \begin{center} - \hspace*{-0.2in}\pgfimage[width=2.5in]{MEDIA/m2/mlab_tui} - \end{center} -\end{frame} - -\begin{frame} - {Exploring the documentation} - \begin{center} - \pgfimage[width=4in]{MEDIA/m2/m2_ug_doc} - \end{center} -\end{frame} - - -\begin{frame} - \frametitle{Summary} - \begin{itemize} - \item \url{http://code.enthought.com/projects/mayavi} - \item Uses VTK (\url{www.vtk.org}) - \item BSD license - \item Linux, win32 and Mac OS X - \item Highly scriptable - \item Embed in Traits UIs (wxPython and PyQt4) - \item Envisage Plugins - \item Debian/Ubuntu/Fedora - \item \alert{Pythonic} - \end{itemize} - - \inctime{10} - -\end{frame} - -\subsection{mlab} - -\begin{frame} - {Overview} - \Large - \begin{itemize} - \item Simple - \item Convenient - \item Full-featured - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - - \frametitle{Getting started} - \myemph{\Large Vanilla:} - \begin{lstlisting}[language=bash] - $ ipython -wthread - \end{lstlisting} - \myemph{\Large with Pylab:} - \begin{lstlisting}[language=bash] - $ ipython -pylab -wthread - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Using mlab} - - \begin{lstlisting} ->>> from enthought.mayavi import mlab - \end{lstlisting} - - \vspace*{0.5in} - - \myemph{\Large Try these} - - \vspace*{0.25in} - - \begin{lstlisting} ->>> mlab.test_ ->>> mlab.test_contour3d() ->>> mlab.test_contour3d?? - \end{lstlisting} -\end{frame} - -\begin{frame} - {Exploring the view} - \begin{columns} - \column{0.6\textwidth} - \pgfimage[width=3in]{MEDIA/m2/contour3d} - \column{0.4\textwidth} - \begin{itemize} - \item Mouse - \item Keyboard - \item Toolbar - \item Mayavi icon\pgfimage[width=0.2in]{MEDIA/m2/m2_icon} - \end{itemize} - \end{columns} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\mlab\ plotting functions} - \begin{columns} - \column{0.25\textwidth} - \myemph{\Large 0D data} - \column{0.5\textwidth} - \pgfimage[width=2in]{MEDIA/m2/mlab/points3d_ex} - \end{columns} - - \begin{lstlisting} ->>> from numpy import * ->>> t = linspace(0, 2*pi, 50) ->>> u = cos(t)*pi ->>> x, y, z = sin(u), cos(u), sin(t) - \end{lstlisting} - \emphbar{\PythonCode{>>> mlab.points3d(x, y, z)}} -\end{frame} - -\begin{frame} - \begin{columns} - \column{0.25\textwidth} - \myemph{\Large 1D data} - \column{0.5\textwidth} - \pgfimage[width=2.5in]{MEDIA/m2/mlab/plot3d_ex} - \end{columns} - \emphbar{\PythonCode{>>> mlab.plot3d(x, y, z, t)}} - - Plots lines between the points - -\end{frame} - -\begin{frame}[fragile] - \begin{columns} - \column{0.25\textwidth} - \myemph{\Large 2D data} - \column{0.5\textwidth} - \pgfimage[width=2in]{MEDIA/m2/mlab/surf_ex} - \end{columns} - \begin{lstlisting} ->>> x = mgrid[-3:3:100j,-3:3:100j] ->>> z = sin(x*x + y*y) - \end{lstlisting} - - \emphbar{\PythonCode{>>> mlab.surf(x, y, z)}} - - \alert{Assumes the points are rectilinear} - -\end{frame} - -\begin{frame}[fragile] - \myemph{\Large 2D data: \texttt{mlab.mesh}} - \vspace*{0.25in} - - \emphbar{\PythonCode{>>> mlab.mesh(x, y, z)}} - - \alert{Points needn't be regular} - - \vspace*{0.25in} -\begin{lstlisting} ->>> phi, theta = numpy.mgrid[0:pi:20j, -... 0:2*pi:20j] ->>> x = sin(phi)*cos(theta) ->>> y = sin(phi)*sin(theta) ->>> z = cos(phi) ->>> mlab.mesh(x, y, z, -... representation= -... 'wireframe') -\end{lstlisting} - -\end{frame} - -\begin{frame}[fragile] - - \begin{columns} - \column{0.25\textwidth} - \myemph{\Large 3D data} - \column{0.5\textwidth} - \pgfimage[width=1.5in]{MEDIA/m2/mlab/contour3d}\\ - \end{columns} -\begin{lstlisting} ->>> x, y, z = ogrid[-5:5:64j, -... -5:5:64j, -... -5:5:64j] ->>> mlab.contour3d(x*x*0.5 + y*y + - z*z*2) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - - \myemph{\Large 3D vector data: \PythonCode{mlab.quiver3d}} - \vspace*{0.25in} - - \pgfimage[width=2in]{MEDIA/m2/mlab/quiver3d_ex}\\ - -\begin{lstlisting} ->>> mlab.test_quiver3d() -\end{lstlisting} - -\emphbar{\PythonCode{obj = mlab.quiver3d(x, y, z, u, v, w)}} -\inctime{20} -\end{frame} - -\begin{frame} - {Getting hands dirty!} - - \begin{block}{Motivational problem} - Atmospheric data of temperature over the surface of the earth. - Let temperature ($T$) vary linearly with height ($z$): - \begin{center} - $T = 288.15 - 6.5z$ - \end{center} - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Simple solution} - - \begin{lstlisting} -lat = linspace(-89, 89, 37) -lon = linspace(0, 360, 37) -z = linspace(0, 100, 11) - \end{lstlisting} -\pause - \begin{lstlisting} -x, y, z = mgrid[0:360:37j,-89:89:37j, - 0:100:11j] -t = 288.15 - 6.5*z -mlab.contour3d(x, y, z, t) -mlab.outline() -mlab.colorbar() - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise: Lorenz equation} - \begin{columns} - \column{0.25\textwidth} - \begin{eqnarray*} - \frac{d x}{dt} &=& s (y-x)\\ - \frac{d y}{d t} &=& rx -y -xz\\ - \frac{d z}{d t} &=& xy - bz\\ - \end{eqnarray*} - \column{0.25\textwidth} - Let $s=10,$ - $r=28,$ - $b=8./3.$ - \end{columns} - \structure{\Large Region of interest} - \begin{lstlisting} -x, y, z = mgrid[-50:50:20j,-50:50:20j, - -10:60:20j] - \end{lstlisting} -\inctime{20} - -\end{frame} -\begin{frame}[fragile] - \frametitle{Solution} - \begin{lstlisting} -def lorenz(x,y,z,s=10.,r=28.,b=8./3.): - u = s*(y-x) - v = r*x-y-x*z - w = x*y-b*z - return u,v,w -x,y,z = mgrid [-50:50:20j,-50:50:20j, - -10:60:20j ] -u,v,w = lorenz( x , y , z ) -# Your plot here -# -mlab.show() - - \end{lstlisting} -\end{frame} - -\end{document} - diff -r ae070c133120 -r 24992ab48f2b day2/tda.tex --- a/day2/tda.tex Wed Oct 14 11:02:18 2009 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,300 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[compress,14pt]{beamer} -% \documentclass[handout]{beamer} -% \usepackage{pgfpages} -% \pgfpagesuselayout{4 on 1}[a4paper,border, shrink=5mm,landscape] -\usepackage{tikz} -\newcommand{\hyperlinkmovie}{} -%\usepackage{movie15} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Note that in presentation mode -% \paperwidth 364.19536pt -% \paperheight 273.14662pt -% h/w = 0.888 - - -\mode -{ - \usetheme{Warsaw} - %\usetheme{Boadilla} - %\usetheme{default} - \useoutertheme{split} - \setbeamercovered{transparent} -} - -% To remove navigation symbols -\setbeamertemplate{navigation symbols}{} - -\usepackage{amsmath} -\usepackage[english]{babel} -\usepackage[latin1]{inputenc} -\usepackage{times} -\usepackage[T1]{fontenc} - -% Taken from Fernando's slides. -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} -\usepackage{pgf} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% My Macros -\setbeamercolor{postit}{bg=yellow,fg=black} -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -%{\centerline{\fcolorbox{gray!50} {blue!10}{ -%\begin{minipage}{0.9\linewidth} -% {#1} -%\end{minipage} -% }}} - -\newcommand{\myemph}[1]{\structure{\emph{#1}}} -\newcommand{\PythonCode}[1]{\lstinline{#1}} - -\newcommand{\tvtk}{\texttt{tvtk}} -\newcommand{\mlab}{\texttt{mlab}} - -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\vspace*{0.1in}\tiny \thetime\ m}} - -\newcommand\BackgroundPicture[1]{% - \setbeamertemplate{background}{% - \parbox[c][\paperheight]{\paperwidth}{% - \vfill \hfill - \hfill \vfill -}}} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Configuring the theme -%\setbeamercolor{normal text}{fg=white} -%\setbeamercolor{background canvas}{bg=black} - - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[]{Test Driven Approach} - -\author[FOSSEE Team] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {11, October 2009} -\date[] % (optional) - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%\pgfdeclareimage[height=0.75cm]{iitblogo}{iitblogo} -%\logo{\pgfuseimage{iitblogo}} - -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \Large - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -%% Delete this, if you do not want the table of contents to pop up at -%% the beginning of each subsection: -\AtBeginSubsection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} - -\AtBeginSection[] -{ - \begin{frame} - \frametitle{Outline} - \tableofcontents[currentsection,currentsubsection] - \end{frame} -} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \maketitle -\end{frame} - -\section{Test Driven Approach} - -\begin{frame} - \frametitle{Testing code with nosetests} - - \begin{itemize} - \item Writing tests is really simple! - - \item Using nose. - - \item Example! - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Need of Testing!} - - \begin{itemize} - \item Quality - - \item Regression - - \item Documentation - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Nosetest} - \begin{lstlisting} -def gcd(a, b): - """Returns gcd of a and b, - handles only positive numbers.""" - if a%b == 0: return b - return gcd(b, a%b) -def lcm(a, b): - return a*b/gcd(a, b) - -if __name__ == '__main__': - import nose - nose.main() - \end{lstlisting} -\inctime{10} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Example} - \begin{block}{Problem Statement:} - Write a function to check whether a given input - string is a palindrome. - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Function: palindrome.py} -\begin{lstlisting} -def is_palindrome(input_str): - return input_str == input_str[::-1] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Test for the palindrome: palindrome.py} -\begin{lstlisting} -from plaindrome import is_palindrome -def test_function_normal_words(): - input = "noon" - assert is_palindrome(input) == True -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Running the tests.} -\begin{lstlisting} -$ nosetests test.py -. ----------------------------------------------- -Ran 1 test in 0.001s - -OK -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Exercise: Including new tests.} -\begin{lstlisting} -def test_function_ignore_cases_words(): - input = "Noon" - assert is_palindrome(input) == True -\end{lstlisting} - \vspace*{0.25in} - Check\\ - \PythonCode{$ nosetests test.py} \\ - \begin{block}{Task} - Tweak the code to pass this test. - \end{block} -\end{frame} - -%\begin{frame}[fragile] -% \frametitle{Lets write some test!} -%\begin{lstlisting} -%#for form of equation y=mx+c -%#given m and c for two equation, -%#finding the intersection point. -%def intersect(m1,c1,m2,c2): -% x = (c2-c1)/(m1-m2) -% y = m1*x+c1 -% return (x,y) -%\end{lstlisting} -% -%Create a simple test for this -% -%function which will make it fail. -% -%\inctime{15} -%\end{frame} -% - -\begin{frame}[fragile] - \frametitle{Exercise} - Based on Euclid's algorithm: - $gcd(a,b)=gcd(b,b\%a)$\\ - gcd function can be written as: - \begin{lstlisting} - def gcd(a, b): - if a%b == 0: return b - return gcd(b, a%b) - \end{lstlisting} - \vspace*{-0.15in} - \begin{block}{Task} - \begin{itemize} - \item Write at least - two tests for above mentioned function. - \item Write a non recursive implementation - of gcd(), and test it using already - written tests. - \end{itemize} - \end{block} - -\inctime{15} -\end{frame} - -\begin{frame}{In this session we have covered:} - \begin{itemize} - \item Need for visualization. - \item Tools available. - \item How to follow Test Driven Approach. - \end{itemize} -\end{frame} -\begin{frame} - \begin{center} - \Huge - Thank you! - \end{center} -\end{frame} - -\end{document}