%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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: \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} \section{Functions and basic data structures} \subsection{Exercises on Control flow} \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}[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{20}} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % TIME: 20 m, running 20m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \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{10} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % TIME: 10 m, running 30m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \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{25} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % TIME: 25 m, running 55m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \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] >>> 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, 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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \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 Defining functions and calling them \item Lists: Creating, Indexing, Slicing and List methods \item Tuples \item range() function \item for loops \item iterating lists with for, for...range() \end{itemize} \end{frame} \end{document}