# HG changeset patch # User Madhusudan.C.S # Date 1257512588 -19800 # Node ID c4e25269a86c2790bdcbac123ada67c1edbf6676 # Parent d4ad532525a2d4b4a68741088f6f6ce282de822b Reorganized slides. diff -r d4ad532525a2 -r c4e25269a86c day1/session3.tex --- a/day1/session3.tex Fri Nov 06 17:56:22 2009 +0530 +++ b/day1/session3.tex Fri Nov 06 18:33:08 2009 +0530 @@ -78,6 +78,7 @@ \author[FOSSEE] {FOSSEE} \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} + \date[] {7 November, 2009\\Day 1, Session 3} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -126,67 +127,88 @@ %% % You might wish to add the option [pausesections] %% \end{frame} +\section{Computing mean} +\begin{frame} + \frametitle{Value of acceleration due to gravity?} + \begin{itemize} + \item We already have pendulum.txt + \item We know that $ T = 2\pi \sqrt{\frac{L}{g}} $ + \item So $ g = \frac{4 \pi^2 L}{T^2} $ + \item Calculate ``g'' - acceleration due to gravity for each pair of L and T + \item Hence calculate mean ``g'' + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Acceleration due to gravity - ``g''\ldots} + \begin{lstlisting} +In []: G = [] +In []: for line in open('pendulum.txt'): + .... points = line.split() + .... l = float(points[0]) + .... t = float(points[1]) + .... g = 4 * pi * pi * l / t * t + .... G.append(g) + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Computing mean ``g''} + \begin{block}{Exercise} + Obtain the mean of ``g'' + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Mean ``g''} + \begin{lstlisting} +total = 0 +for g in G: + total += g + +mean_g = total / len(g) +print "Mean: ", mean_g + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Mean ``g''} + \begin{lstlisting} +mean_g = sum(G) / len(G) +print "Mean: ", mean_g + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Mean ``g''} + \begin{lstlisting} +mean_g = mean(G) +print "Mean: ", mean_g + \end{lstlisting} + \inctime{10} +\end{frame} + \section{Processing voluminous data} \begin{frame} \frametitle{More on data processing} \begin{block}{} - We have a huge--1m records--data file.\\How do we do \emph{efficient} statistical computations, that is find mean, median, mode, standard deveiation etc; draw pie charts? + We have a huge data file--180,000 records.\\How do we do \emph{efficient} statistical computations, i.e. find mean, median, standard deviation etc; draw pie charts? \end{block} \end{frame} - -\begin{frame} - \frametitle{Statistical Analysis: Problem statement} - Read the data supplied in \emph{sslc1.txt} and carry out the following: - \begin{enumerate} - \item Draw a pie chart representing the proportion of students who scored more than 90\% in each region in Science. - \item Draw a pie chart representing the proportion of students who scored more than 90\% in each subject across regions. - \item Print mean, median, mode and standard deviation of math scores for all regions combined. - \end{enumerate} -\end{frame} - -\begin{frame} - \frametitle{Problem statement: explanation} - \emphbar{Draw a pie chart representing the proportion of students who scored more than 90\% in each region in Science.} - \begin{enumerate} - \item Complete(100\%) data - Number of students who scored more than 90\% in Science - \item Each slice - Number of students who scored more than 90\% in Science in one region - \end{enumerate} -\end{frame} - \begin{frame} - \frametitle{Problem statement: explanation} - \emphbar{Draw a pie chart representing the proportion of students who scored more than 90\% in each subject across regions.} - \begin{enumerate} - \item Complete(100\%) data - Number of students who scored more than 90\% across all regions - \item Each slice - Number of students who scored more than 90\% in each subject across all regions - \end{enumerate} + \frametitle{Structure of the file} + Understanding the structure of sslc1.txt + \begin{itemize} + \item Each line in the file has a student's details(record) + \item Each record consists of fields separated by ';' + \end{itemize} +\emphbar{A;015162;JENIL T P;081;060;77;41;74;333;P;;} \end{frame} \begin{frame} - \frametitle{Statistical Analysis and Parsing \ldots} - Machinery Required - - \begin{itemize} - \item File reading - \item Parsing - \item Dictionaries - \item NumPy arrays - \item Statistical operations - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{File reading and parsing} - Understanding the structure of sslc1.txt - \begin{itemize} - \item One line in file corresponds to a student's details - \item aka record - \item Each record consists of fields separated by ';' - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{File reading and parsing \ldots} + \frametitle{Structure of the file \ldots} +\emphbar{A;015163;JOSEPH RAJ S;083;042;47;AA;72;244;;;} Each record consists of: \begin{itemize} \item Region Code @@ -195,11 +217,43 @@ \item Marks of 5 subjects: English, Hindi, Maths, Science, Social \item Total marks \item Pass/Fail (P/F) - \item Withdrawn (W) + \item Withheld (W) \end{itemize} \inctime{5} \end{frame} +\begin{frame} + \frametitle{Statistical Analysis: Problem statement} + 1. Read the data supplied in the file \emph{sslc1.txt} and carry out the following: + \begin{itemize} + \item[a] Draw a pie chart representing proportion of students who scored more than 90\% in each region in Science. + \item[b] Print mean, median and standard deviation of math scores for all regions combined. + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Problem statement: explanation} + \emphbar{a. Draw a pie chart representing proportion of students who scored more than 90\% in each region in Science.} +\begin{columns} + \column{5.25\textwidth} + \hspace*{.5in} +\includegraphics[height=2.6in, interpolate=true]{data/science} + \column{0.8\textwidth} +\end{columns} +\end{frame} + +\begin{frame} + \frametitle{Machinery Required} + \begin{itemize} + \item File reading + \item Parsing + \item Dictionaries + \item List enumeration + \item Arrays + \item Statistical operations + \end{itemize} +\end{frame} + \subsection{Data processing} \begin{frame}[fragile] \frametitle{File reading and parsing \ldots} @@ -207,100 +261,71 @@ for record in open('sslc1.txt'): fields = record.split(';') \end{lstlisting} +\begin{block}{} +\centerline{Recall pendulum example!} +\end{block} \end{frame} -\subsection{Dictionary} +\subsection{Dictionaries} \begin{frame}[fragile] - \frametitle{Dictionary: Introduction} + \frametitle{Dictionaries: Introduction} \begin{itemize} \item lists index: 0 \ldots n \item dictionaries index using strings \end{itemize} - \begin{block}{Example} -d = \{ ``Hitchhiker's guide'' : 42, - ``Terminator'' : ``I'll be back''\}\\ -d[``Terminator''] => ``I'll be back'' - \end{block} \end{frame} \begin{frame}[fragile] - \frametitle{Dictionary: Introduction} + \frametitle{Dictionaries \ldots} \begin{lstlisting} -In [1]: d = {"Hitchhiker's guide" : 42, - "Terminator" : "I'll be back"} +In []: d = {"jpg" : "image file", + "txt" : "text file", + "py" : "python code"} -In [2]: d["Hitchhiker's guide"] -Out[2]: 42 - -In [3]: "Hitchhiker's guide" in d -Out[3]: True - -In [4]: "Guido" in d -Out[4]: False +In []: d["txt"] +Out[]: 'text file' \end{lstlisting} \end{frame} \begin{frame}[fragile] - \frametitle{Dictionary: Introduction} + \frametitle{Dictionaries \ldots} \begin{lstlisting} -In [5]: d.keys() -Out[5]: ['Terminator', "Hitchhiker's - guide"] +In []: "py" in d +Out[]: True -In [6]: d.values() -Out[6]: ["I'll be back", 42] +In []: "cpp" in d +Out[]: False \end{lstlisting} \end{frame} \begin{frame}[fragile] - \frametitle{Back to lists: Iterating} - \begin{itemize} - \item Python's \kwrd{for} loop iterates through list items - \item In other languages (C/C++) we run through indices and pick items from the array using these indices - \item In Python, while iterating through list items current position is not available - \end{itemize} - \begin{block}{Iterating through indices} - What if we want the index of an item of a list? - \end{block} + \frametitle{Dictionaries \ldots} + \begin{lstlisting} +In []: d.keys() +Out[]: ['py', 'txt', 'jpg'] +In []: d.values() +Out[]: ['python code', 'text file', + 'image file'] + \end{lstlisting} + \inctime{10} \end{frame} \begin{frame}[fragile] - \frametitle{enumerate: Iterating through list indices} - \begin{lstlisting} -In [1]: names = ["Guido","Alex", "Tim"] - -In [2]: for i, name in enumerate(names): - ...: print i, name - ...: -0 Guido -1 Alex -2 Tim - \end{lstlisting} - \inctime{5} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Continuing with our Dictionary} + \frametitle{Getting back to the problem} Let our dictionary be: \begin{lstlisting} -science = {} # is an empty dictionary +science = {} \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Dictionary - Building parsed data} - \begin{itemize} - \item \emph{Keys} of \emph{science} will be region codes - \item Value of a \emph{science} will be the number students who scored more than 90\% in that region +\begin{itemize} + \item Keys will be region codes + \item Values will be the number students who scored more than 90\% in that region \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Building parsed data \ldots} \begin{lstlisting} -from pylab import pie - science = {} for record in open('sslc1.txt'): @@ -317,9 +342,9 @@ if region_code not in science: science[region_code] = 0 -score_str = fields[4].strip() +score_str = fields[6].strip() -score = int(score_str) if +score = int(score_str) if \ score_str != 'AA' else 0 if score > 90: @@ -327,17 +352,25 @@ \end{lstlisting} \end{frame} +\begin{frame}[fragile] + \frametitle{Building parsed data \ldots} + \begin{lstlisting} +print science +print science.keys() +print science.values() + \end{lstlisting} +\end{frame} + \subsection{Visualizing data} \begin{frame}[fragile] - \frametitle{Pie charts} + \frametitle{Pie chart} \small \begin{lstlisting} -figure(1) pie(science.values(), - labels=science.keys()) + labels = science.keys()) title('Students scoring 90% and above in science by region') -savefig('/tmp/science.png') +savefig('science.png') \end{lstlisting} \begin{columns} \column{5.25\textwidth} @@ -345,148 +378,65 @@ \includegraphics[height=2in, interpolate=true]{data/science} \column{0.8\textwidth} \end{columns} - \inctime{5} + \inctime{10} +\end{frame} + +\begin{frame} + \frametitle{Problem statement} + \emphbar{b. Print mean, median and standard deviation of math scores for all regions combined.} \end{frame} \begin{frame}[fragile] - \frametitle{Building data for all subjects \ldots} + \frametitle{Building data for statistics} \begin{lstlisting} -from pylab import pie -from scipy import mean, median, std -from scipy import stats +math_scores = [] -scores = [[], [], [], [], []] -ninety_percents = [{}, {}, {}, {}, {}] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Building data for all subjects \ldots} - \begin{lstlisting} for record in open('sslc1.txt'): record = record.strip() fields = record.split(';') - region_code = fields[0].strip() - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Building data for all subjects \ldots} - \small - \begin{lstlisting} -for i, field in enumerate(fields[3:8]): - if region_code not in ninety_percents[i]: - ninety_percents[i][region_code] = 0 - - score_str = field.strip() - score = int(score_str) if + score_str = fields[5].strip() + score = int(score_str) if \ score_str != 'AA' else 0 - scores[i].append(score) - - if score > 90: - ninety_percents[i][region_code] += 1 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Consolidating data} - \begin{lstlisting} -subj_total = [] -for subject in ninety_percents: - subj_total.append(sum( - subject.values())) + math_scores.append(score) \end{lstlisting} \end{frame} -\begin{frame}[fragile] - \frametitle{Pie charts} - \begin{lstlisting} -figure(2) -pie(subj_total, labels=['English', - 'Hindi', 'Maths', 'Science', - 'Social']) -title('Students scoring more than - 90% by subject(All regions - combined).') -savefig('/tmp/all_regions.png') - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Pie charts} - \includegraphics[height=3in, interpolate=true]{data/all_regions} -\end{frame} - \subsection{Obtaining statistics} \begin{frame}[fragile] \frametitle{Obtaining statistics} - \begin{block}{Statistics: Mean} + \begin{block}{Exercise} Obtain the mean of Math scores \end{block} \end{frame} \begin{frame}[fragile] - \frametitle{Obtaining statistics: Solution} - \begin{block}{Statistics: Mean} - Obtain the mean of Math scores - \end{block} - \begin{lstlisting} -math_scores = scores[2] -total = 0 -for i, score in enumerate(math_scores): - total += score - -mean = total / (i + 1) -print "Mean: ", mean - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Obtaining statistics: Another solution} - \begin{block}{Statistics: Mean} - Obtain the mean of Math scores - \end{block} - \begin{lstlisting} -math_scores = scores[2] -mean = sum(math_scores) / - len(math_scores) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] -\frametitle{NumPy arrays} - \begin{itemize} - \item NumPy provides arrays - \item arrays are very efficient and powerful - \item Very easy to perform element-wise operations - \typ{+, -, *, /, \%} - \begin{lstlisting} -In [1]: a = array([1, 2, 3]) -In [2]: b = array([4, 5, 6]) - -In [3]: a + b -Out[3]: array([5, 7, 9]) - \end{lstlisting} - \item Very easy to compute statistics - \end{itemize} -\end{frame} - -\begin{frame}[fragile] \frametitle{Obtaining statistics} \begin{lstlisting} -math_scores = array(scores[2]) - print "Mean: ", mean(math_scores) print "Median: ", median(math_scores) -print "Mode: ", stats.mode(math_scores) - print "Standard Deviation: ", std(math_scores) \end{lstlisting} - \inctime{15} + \inctime{10} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Obtaining statistics: efficiently!} + \begin{lstlisting} +math_array = array(math_scores) + +print "Mean: ", mean(math_array) + +print "Median: ", median(math_array) + +print "Standard Deviation: ", + std(math_array) + \end{lstlisting} + \inctime{5} \end{frame} \begin{frame}[fragile] @@ -494,37 +444,9 @@ \begin{itemize} \item Dictionaries for storing data \item Facilities for drawing pie charts - \item NumPy arrays for efficient array manipulations - \item Functions for statistical computations - mean, median, mode, standard deviation + \item Efficient array manipulations + \item Functions for statistical computations - mean, median, standard deviation \end{itemize} \end{frame} -\section{Least square fit} -\begin{frame} -\frametitle{L vs $T^2$ \ldots} -Let's go back to the L vs $T^2$ plot -\begin{itemize} -\item We first look at obtaining $T^2$ from T -\item Then, we look at plotting a Least Squares fit -\end{itemize} -\end{frame} - -\begin{frame}[fragile] -\frametitle{Dealing with data whole-sale} -\begin{lstlisting} -In []: for t in T: - ....: TSq.append(t*t) -\end{lstlisting} -\begin{itemize} -\item This is not very efficient -\item We are squaring element after element -\item We use arrays to make this efficient -\end{itemize} -\begin{lstlisting} -In []: L = array(L) -In []: T = array(T) -In []: TSq = T*T -\end{lstlisting} -\end{frame} - \end{document} diff -r d4ad532525a2 -r c4e25269a86c day2/session1.tex --- a/day2/session1.tex Fri Nov 06 17:56:22 2009 +0530 +++ b/day2/session1.tex Fri Nov 06 18:33:08 2009 +0530 @@ -1,8 +1,8 @@ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Tutorial slides on Python. % -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran +% Author: FOSSEE +% Copyright (c) 2009, FOSSEE, IIT Bombay %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \documentclass[14pt,compress]{beamer} @@ -78,7 +78,7 @@ \author[FOSSEE Team] {The FOSSEE Group} \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {1, November 2009\\Day 2, Session 1} +\date[] {8 November, 2009\\Day 2, Session 1} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} @@ -140,13 +140,13 @@ \begin{itemize} \item \kwrd{int}\\ \kwrd{int} = whole number, no matter what the size! \begin{lstlisting} -In [1]: a = 13 +In []: a = 13 -In [2]: b = 99999999999999999999 +In []: b = 99999999999999999999 \end{lstlisting} \item \kwrd{float} \begin{lstlisting} -In [3]: fl = 3.141592 +In []: p = 3.141592 \end{lstlisting} \end{itemize} \end{frame} @@ -154,16 +154,16 @@ \begin{frame}[fragile] \frametitle{Complex numbers} \begin{lstlisting} -In [1]: cplx = 3+4j +In []: c = 3+4j -In [2]: abs(cplx) -Out[2]: 5.0 +In []: abs(c) +Out[]: 5.0 -In [3]: cplx.imag -Out[3]: 4.0 +In []: c.imag +Out[]: 4.0 -In [4]: cplx.real -Out[4]: 3.0 +In []: c.real +Out[]: 3.0 \end{lstlisting} \end{frame} @@ -171,16 +171,31 @@ \begin{frame}[fragile] \frametitle{Boolean} \begin{lstlisting} -In [1]: t = True +In []: t = True + +In []: f = not t -In [2]: f = not t -Out[2]: False +In []: f or t +Out[]: True + +In []: f and t +Out[]: False + \end{lstlisting} + \inctime{5} +\end{frame} -In [3]: f or t -Out[3]: True +\begin{frame}[fragile] + \frametitle{( ) for precedence} + \begin{lstlisting} +In []: a = False +In []: b = True +In []: c = True -In [4]: f and t -Out[4]: False +In []: (a and b) or c +Out[]: True + +In []: a and (b or c) +Out[]: False \end{lstlisting} \inctime{5} \end{frame} @@ -191,20 +206,20 @@ \frametitle{Strings} Strings were introduced previously, let us now look at them in a little more detail. \begin{lstlisting} -In [1]: w = "hello" +In []: w = "hello" -In [2]: print w[0] + w[2] + w[-1] -Out[2]: hlo +In []: print w[0] + w[2] + w[-1] +Out[]: hlo -In [3]: len(w) # guess what -Out[3]: 5 +In []: len(w) # guess what +Out[]: 5 \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Strings \ldots} \begin{lstlisting} -In [1]: w[0] = 'H' # Can't do that! +In []: w[0] = 'H' # Can't do that! -------------------------------------------- TypeError Traceback (most recent call last) @@ -218,19 +233,35 @@ \begin{frame}[fragile] \frametitle{String methods} \begin{lstlisting} -In [1]: a = 'Hello World' -In [2]: a.startswith('Hell') -Out[2]: True +In []: a = 'Hello World' +In []: a.startswith('Hell') +Out[]: True + +In []: a.endswith('ld') +Out[]: True -In [3]: a.endswith('ld') -Out[3]: True +In []: a.upper() +Out[]: 'HELLO WORLD' + +In []: a.lower() +Out[]: 'hello world' + \end{lstlisting} +\end{frame} -In [4]: a.upper() -Out[4]: 'HELLO WORLD' - -In [5]: a.lower() -Out[5]: 'hello world' - \end{lstlisting} +\begin{frame} + \frametitle{A bit about IPython} + \begin{itemize} + \item IPython provides better help + \item object.function? + \begin{lstlisting} +In []: a = 'Hello World' +In []: a.lower? + \end{lstlisting} + \item It provides tab completion + \begin{lstlisting} +In []: a.s + \end{lstlisting} + \end{itemize} \end{frame} \begin{frame}[fragile] @@ -240,77 +271,102 @@ \item join() is the opposite of split() \end{itemize} \begin{lstlisting} -In [1]: ''.join(['a', 'b', 'c']) -Out[1]: 'abc' +In []: ''.join(['a', 'b', 'c']) +Out[]: 'abc' \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{String formatting} \begin{lstlisting} -In [1]: x, y = 1, 1.234 +In []: x, y = 1, 1.234 -In [2]: 'x is %s, y is %s' %(x, y) -Out[2]: 'x is 1, y is 1.234' +In []: 'x is %s, y is %s' %(x, y) +Out[]: 'x is 1, y is 1.234' \end{lstlisting} + \begin{itemize} + \item \emph{\%d}, \emph{\%f} etc. available + \end{itemize} \emphbar{\url{http://docs.python.org/library/stdtypes.html}} \inctime{10} \end{frame} \section{Operators} \begin{frame}[fragile] - \frametitle{Arithematic operators} + \frametitle{Arithmetic operators} \begin{lstlisting} -In [1]: 1786 % 12 -Out[1]: 10 +In []: 1786 % 12 +Out[]: 10 + +In []: 45 % 2 +Out[]: 1 -In [2]: 3124 * 126789 -Out[2]: 396088836 +In []: 864675 % 10 +Out[]: 5 -In [3]: a = 3124 * 126789 +In []: 3124 * 126789 +Out[]: 396088836 -In [4]: big = 1234567891234567890 ** 3 +In []: big = 1234567891234567890 ** 3 -In [5]: verybig = big * big * big * big +In []: verybig = big * big * big * big \end{lstlisting} \end{frame} \begin{frame}[fragile] - \frametitle{Arithematic operators \ldots} + \frametitle{Arithmetic operators} \begin{lstlisting} -In [1]: 17/2 -Out[1]: 8 +In []: 17 / 2 +Out[]: 8 + +In []: 17 / 2.0 +Out[]: 8.5 + +In []: 17.0 / 2 +Out[]: 8.5 + +In []: 17.0 / 8.5 +Out[]: 2.0 + \end{lstlisting} +\end{frame} -In [2]: 17/2.0 -Out[2]: 8.5 +\begin{frame}[fragile] + \frametitle{Arithmetic operators} + \begin{lstlisting} +In []: a = 7546 -In [3]: 17.0/2 -Out[3]: 8.5 +In []: a += 1 +In []: a +Out[]: 7547 -In [4]: 17.0/8.5 -Out[4]: 2.0 +In []: a -= 5 +In []: a + +In []: a *= 2 + +In []: a /= 5 \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{String operations} \begin{lstlisting} -In [1]: s = 'Hello ' +In []: s = 'Hello ' -In [2]: p = 'World' +In []: p = 'World' -In [3]: s + p -Out[3]: 'Hello World' +In []: s + p +Out[]: 'Hello World' -In [4]: s * 4 -Out[4]: 'Hello Hello Hello Hello' +In []: s * 4 +Out[]: 'Hello Hello Hello Hello' \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{String operations \ldots} \begin{lstlisting} -In [1]: s * s +In []: s * s -------------------------------------------- TypeError Traceback (most recent call last) @@ -324,35 +380,35 @@ \begin{frame}[fragile] \frametitle{Relational and logical operators} \begin{lstlisting} -In [1]: pos, zer, neg = 1, 0, -1 -In [2]: pos == neg -Out[2]: False +In []: p, z, n = 1, 0, -1 +In []: p == n +Out[]: False -In [3]: pos >= neg -Out[3]: True +In []: p >= n +Out[]: True -In [4]: neg < zer < pos -Out[4]: True +In []: n < z < p +Out[]: True -In [5]: pos + neg != zer -Out[5]: False +In []: p + n != z +Out[]: False \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Built-ins} \begin{lstlisting} -In [1]: int(17/2.0) -Out[1]: 8 +In []: int(17 / 2.0) +Out[]: 8 -In [2]: float(17/2) # Recall -Out[2]: 8.0 +In []: float(17 / 2) # Recall +Out[]: 8.0 -In [3]: str(17/2.0) -Out[3]: '8.5' +In []: str(17 / 2.0) +Out[]: '8.5' -In [4]: round( 7.5 ) -Out[4]: 8.0 +In []: round( 7.5 ) +Out[]: 8.0 \end{lstlisting} \end{frame} @@ -362,15 +418,15 @@ \item Case sensitive \item Dynamically typed $\Rightarrow$ need not specify a type \begin{lstlisting} -In [1]: a = 1 -In [2]: a = 1.1 -In [3]: a = "Now I am a string!" +In []: a = 1 +In []: a = 1.1 +In []: a = "Now I am a string!" \end{lstlisting} \item Comments: \begin{lstlisting} -In [4]: a = 1 # In-line comments -In [5]: # A comment line. -In [6]: a = "# Not a comment!" +In []: a = 1 # In-line comments +In []: # A comment line. +In []: a = "# Not a comment!" \end{lstlisting} \end{itemize} \inctime{15} @@ -379,14 +435,15 @@ \section{Simple IO} \begin{frame}[fragile] \frametitle{Simple IO: Console Input} + \small \begin{itemize} \item raw\_input() waits for user input. \begin{lstlisting} -In [1]: a = raw_input() +In []: a = raw_input() 5 -In [2]: a = raw_input('prompt > ') -prompt > 5 +In []: a = raw_input('Enter a value: ') +Enter a value: 5 \end{lstlisting} \item Prompt string is optional. \item All keystrokes are Strings! @@ -394,11 +451,36 @@ \end{itemize} \end{frame} -\begin{frame}{Simple IO: Console output} +\begin{frame}[fragile] + \frametitle{Simple IO: Console output} \begin{itemize} \item \texttt{print} is straight forward - \item Note the distinction between \texttt{print x} and \texttt{print x,} + \item Put the following code snippet in a file \end{itemize} + \begin{lstlisting} +print "Hello" +print "World" + + +In []: %run -i hello1.py +Hello +World + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Simple IO: Console output \ldots} +Put the following code snippet in a file + \begin{lstlisting} +print "Hello", +print "World" + + +In []: %run -i hello2.py +Hello World + \end{lstlisting} + +\emphbar{Note the distinction between \texttt{print x} and \texttt{print x,}} \end{frame} \section{Control flow} @@ -406,8 +488,9 @@ \frametitle{Control flow constructs} \begin{itemize} \item \kwrd{if/elif/else}: branching + \item \kwrd{C if X else Y}: Ternary conditional operator \item \kwrd{while}: looping - \item \kwrd{for}: iterating + \item \kwrd{for}: iterating \item \kwrd{break, continue}: modify loop \item \kwrd{pass}: syntactic filler \end{itemize} @@ -416,101 +499,41 @@ \subsection{Basic Conditional flow} \begin{frame}[fragile] \frametitle{\typ{If...elif...else} example} + \small \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' +In []: x = int(raw_input("Enter an integer:")) + +In []: if x < 0: + ...: print 'Be positive!' + ...: elif x == 0: + ...: print 'Zero' + ...: elif x == 1: + ...: print 'Single' + ...: else: + ...: print 'More' + ...: + ...: \end{lstlisting} \inctime{10} \end{frame} -\subsection{Basic Looping} \begin{frame}[fragile] - \frametitle{\typ{while}} -Example: Fibonacci series - \begin{lstlisting} -# 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}\\ -\end{frame} - -\begin{frame}[fragile] -\frametitle{\typ{range()}} -\kwrd{range([start,] stop[, step])}\\ -\begin{itemize} - \item range() returns a list of integers - \item The \emph{start} and the \emph{step} arguments are optional - \item \emph{stop} argument is not included in the list -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{for} \ldots \typ{range()}} -Example: print squares of first \typ{n} numbers + \frametitle{Ternary conditional operator} \begin{lstlisting} -In []: for i in range(5): - ....: print i, i * i - ....: - ....: -0 0 -1 1 -2 4 -3 9 -4 16 -\end{lstlisting} -\inctime{5} -\end{frame} - -\subsection{Exercises} - -\begin{frame}{Problem set 1: 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.3} - Write a program that prints the following pyramid on the screen. - \begin{lstlisting} -1 -2 2 -3 3 3 -4 4 4 4 +... +a = raw_input('Enter number(Q to quit):') +num = int(a) if a != 'Q' else break +... \end{lstlisting} -The number of lines must be obtained from the user as input.\\ -\pause -\emphbar{When can your code fail?} -\inctime{5} \end{frame} \begin{frame}[fragile] \frametitle{What did we learn?} \begin{itemize} - \item Basic data types - \item Operators - \item Conditional structures - \item Loops + \item Data types: int, float, complex, boolean, string + \item Operators: +, -, *, /, \%, **, +=, -=, *=, /=, >, <, <=, >=, ==, !=, a < b < c + \item Simple IO: \kwrd{raw\_input} and \kwrd{print} + \item Conditional structures: \kwrd{if/elif/else},\\ \kwrd{C if X else Y} \end{itemize} \end{frame} diff -r d4ad532525a2 -r c4e25269a86c day2/session2.tex --- a/day2/session2.tex Fri Nov 06 17:56:22 2009 +0530 +++ b/day2/session2.tex Fri Nov 06 18:33:08 2009 +0530 @@ -1,8 +1,8 @@ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Tutorial slides on Python. % -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran +% Author: FOSSEE +% Copyright (c) 2009, FOSSEE, IIT Bombay %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \documentclass[14pt,compress]{beamer} @@ -78,7 +78,7 @@ \author[FOSSEE Team] {The FOSSEE Group} \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {1, November 2009\\Day 2, Session 2} +\date[] {8 November, 2009\\Day 2, Session 2} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} @@ -123,13 +123,113 @@ % You might wish to add the option [pausesections] \end{frame} +\section{Control flow} +\subsection{Basic Looping} +\begin{frame}[fragile] + \frametitle{\typ{while}} +Example: Fibonacci series + \begin{lstlisting} +# the sum of two elements +# defines the next +In []: a, b = 0, 1 +In []: while b < 10: + ...: print b, + ...: a, b = b, a + b + ...: + ...: +\end{lstlisting} +\typ{1 1 2 3 5 8}\\ +\end{frame} + +\begin{frame}[fragile] +\frametitle{\typ{range()}} +\kwrd{range([start,] stop[, step])}\\ +\begin{itemize} + \item range() returns a list of integers + \item The \emph{start} and the \emph{step} arguments are optional + \item \emph{stop} argument is not included in the list +\end{itemize} +\vspace*{.5in} +\begin{itemize} + \item \alert{Anything within \typ{[]} is optional} + \begin{itemize} + \item Nothing to do with Python. + \end{itemize} +\end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for} \ldots \typ{range()}} +Example: print squares of first \typ{n} numbers + \begin{lstlisting} +In []: 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} \ldots \typ{range()}} +Example: print squares of odd numbers from 3 to 9 + \begin{lstlisting} +In []: for i in range(3, 10, 2): + ....: print i, i * i + ....: + ....: +3 9 +5 25 +7 49 +9 81 +\end{lstlisting} +\inctime{5} +\end{frame} + +\subsection{Exercises} + +\begin{frame}{Problem set 1: 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.3} + 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.\\ +\pause +\emphbar{When can your code fail?} +\inctime{5} +\end{frame} + \section{Data structures} \subsection{Lists} \begin{frame}[fragile] \frametitle{Lists} \begin{block}{We already know that} \begin{lstlisting} -num = [1, 2, 3, 4, 5, 6, 7, 8] +num = [1, 2, 3, 4] \end{lstlisting} \centerline{is a list} \end{block} @@ -138,29 +238,76 @@ \begin{frame}[fragile] \frametitle{Lists: methods} \begin{lstlisting} +In []: num = [1, 2, 3, 4] + +In []: num.append([9, 10, 11]) + +In []: num +Out[]: [1, 2, 3, 4, [9, 10, 11]] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists: methods} + \begin{lstlisting} +In []: num = [1, 2, 3, 4] + +In []: num.extend([5, 6, 7]) +In []: num +Out[]: [1, 2, 3, 4, 5, 6, 7] + In []: num.reverse() In []: num -Out[]: [8, 7, 6, 5, 4, 3, 2, 1] +Out[]: [7, 6, 5, 4, 3, 2, 1] -In []: num.extend([0, -1, -2]) +In []: num.remove(6) In []: num -Out[]: [8, 7, 6, 5, 4, 3, 2, 1, 0, -1] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists: slicing} + \begin{itemize} + \item \typ{list[initial:final]} + \end{itemize} +\begin{lstlisting} +In []: a = [1, 2, 3, 4, 5] + +In []: a[1:3] +Out[]: [2, 3] + +In []: a[1:-1] +Out[]: [2, 3, 4] -In []: num.remove(0) -In []: num -Out[]: [8, 7, 6, 5, 4, 3, 2, 1, -1] - \end{lstlisting} +In []: a[:3] +Out[]: [1, 2, 3] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists: slicing} + \begin{itemize} + \item \typ{list[initial:final:step]} + \end{itemize} +\begin{lstlisting} +In []: a[1:-1:2] +Out[]: [2, 4] + +In []: a[::2] +Out[]: [1, 3, 5] + +In []: a[-1::-1] +Out[]: [5, 4, 3, 2, 1] +\end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{List containership} \begin{lstlisting} -In []: a = 8 - -In []: a in num +In []: 4 in num Out[]: True -In []: b = 10 +In []: b = 15 In []: b in num Out[]: False @@ -174,9 +321,14 @@ \frametitle{Tuples: Immutable lists} \begin{lstlisting} In []: t = (1, 2, 3, 4, 5, 6, 7, 8) + In []: t[0] + t[3] + t[-1] Out[]: 13 + +# Try the following! +In []: t[4] = 7 \end{lstlisting} +\pause \begin{block}{Note:} \begin{itemize} \item Tuples are immutable - cannot be changed @@ -200,7 +352,7 @@ \subsection{Dictionaries} \begin{frame}[fragile] - \frametitle{Dictionaries: Recall} + \frametitle{Dictionaries: recall} \begin{lstlisting} In []: player = {'Mat': 134,'Inn': 233, 'Runs': 10823, 'Avg': 52.53} @@ -214,6 +366,28 @@ \end{block} \end{frame} +\begin{frame}[fragile] + \frametitle{Dictionaries: containership} + \begin{lstlisting} +In []: 'Inn' in player +Out[]: True + +In []: 'Econ' in player +Out[]: False + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries: methods} + \begin{lstlisting} +In []: player.keys() +Out[]: ['Runs', 'Inn', 'Avg', 'Mat'] + +In []: player.values() +Out[]: [10823, 233, 52.530000000000001, 134] + \end{lstlisting} +\end{frame} + \begin{frame} {Problem Set 2.1: Problem 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. \end{frame} @@ -228,32 +402,47 @@ \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]) + +In []: f10 = set([1,2,3,5,8]) + +In []: p10 = set([2,3,5,7]) + +In []: f10 | p10 +Out[]: set([1, 2, 3, 5, 7, 8]) \end{lstlisting} \end{frame} \begin{frame}[fragile] - \frametitle{Set} + \frametitle{Set \ldots} \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 +In []: f10 & p10 +Out[]: set([2, 3, 5]) + +In []: f10 - p10 +Out[]: set([1, 8]) + +In []: p10 - f10, f10 ^ p10 +Out[]: (set([7]), set([1, 7, 8])) + +In []: set([2,3]) < p10 +Out[]: True +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Set \ldots} + \begin{lstlisting} +In []: set([2,3]) <= p10 +Out[]: True + +In []: 2 in p10 +Out[]: True + +In []: 4 in p10 +Out[]: False + +In []: len(f10) +Out[]: 5 \end{lstlisting} \end{frame} @@ -261,7 +450,14 @@ \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 missing numbers in the given range. +\end{description} +\inctime{15} +\end{frame} + +\begin{frame} + \frametitle{Problem set 2.2} + \begin{description} + \item[2.2.2] Given a list of words, find all the anagrams in the list \end{description} \inctime{15} \end{frame} @@ -294,6 +490,19 @@ \end{frame} \begin{frame}[fragile] + \frametitle {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 ): @@ -304,219 +513,13 @@ \end{lstlisting} \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{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} - -\subsection{Exercises} -\begin{frame}{Problem set 3: Problem 3.1} - Write a function to return the gcd of two numbers. -\end{frame} - -\begin{frame}{Problem 3.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 3.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).} -\inctime{15} -\end{frame} - -\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} + \frametitle{What did we learn?} \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} -\inctime{5} -\end{frame} - -\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{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{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{5} -\end{frame} - -\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 + \item Loops: \kwrd{while}, \kwrd{for} + \item Advanced Data structures + \item Functions \end{itemize} \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} -\inctime{10} -\end{frame} - -\begin{frame} - \frametitle{What did we learn?} - \begin{itemize} - \item Lists, Tuples, Dictionaries, Sets: creation and manipulation - \item More about functions - \item Coding style - \item Objects: creation and manipulation - \end{itemize} -\end{frame} - -\end{document} +\end{document} \ No newline at end of file diff -r d4ad532525a2 -r c4e25269a86c day2/session3.tex --- a/day2/session3.tex Fri Nov 06 17:56:22 2009 +0530 +++ b/day2/session3.tex Fri Nov 06 18:33:08 2009 +0530 @@ -1,48 +1,33 @@ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. +%Tutorial slides on Python. % -% Author: Prabhu Ramachandran -% Copyright (c) 2005-2009, Prabhu Ramachandran +% Author: FOSSEE +% Copyright (c) 2009, FOSSEE, IIT Bombay %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -\documentclass[compress,14pt]{beamer} -% \documentclass[handout]{beamer} -% \usepackage{pgfpages} -% \pgfpagesuselayout{4 on 1}[a4paper,border, shrink=5mm,landscape] -\usepackage{tikz} -\newcommand{\hyperlinkmovie}{} -%\usepackage{movie15} +\documentclass[14pt,compress]{beamer} +%\documentclass[draft]{beamer} +%\documentclass[compress,handout]{beamer} +%\usepackage{pgfpages} +%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Note that in presentation mode -% \paperwidth 364.19536pt -% \paperheight 273.14662pt -% h/w = 0.888 - - +% Modified from: generic-ornate-15min-45min.de.tex \mode { \usetheme{Warsaw} - %\usetheme{Boadilla} - %\usetheme{default} \useoutertheme{infolines} \setbeamercovered{transparent} } -% To remove navigation symbols -\setbeamertemplate{navigation symbols}{} - -\usepackage{amsmath} \usepackage[english]{babel} \usepackage[latin1]{inputenc} -\usepackage{times} +%\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} @@ -55,65 +40,50 @@ keywordstyle=\color{blue}\bfseries} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% My Macros -\setbeamercolor{postit}{bg=yellow,fg=black} +% Macros \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{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} + +\newcommand{\typ}[1]{\texttt{#1}} + +\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } -\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} - +%%% 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[3D Plotting]{3D data Visualization} +\title[Basic Python]{Python language: Data structures and functions} -\author[FOSSEE] {FOSSEE} +\author[FOSSEE Team] {The FOSSEE Group} \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {1 November, 2009\\Day 2, Session 5} - +\date[] {8 November, 2009\\Day 2, Session 3} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%\pgfdeclareimage[height=0.75cm]{iitblogo}{iitblogo} -%\logo{\pgfuseimage{iitblogo}} +%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} +%\logo{\pgfuseimage{iitmlogo}} -\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: @@ -132,12 +102,19 @@ \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 + \titlepage \end{frame} \begin{frame} @@ -146,413 +123,325 @@ % You might wish to add the option [pausesections] \end{frame} -\section{3D Data Visualization} +\section{Functions} +\subsection{Default arguments} +\begin{frame}[fragile] + \frametitle{Functions: default arguments} + \begin{lstlisting} +In []: greet = 'hello world' -\begin{frame} - \frametitle{What is visualization?} - \Large - \begin{center} - Visual representation of data - \end{center} +In []: greet.split() +Out[]: ['hello', 'world'] + +In []: line = 'Rossum, Guido, 54, 46, 55' + +In []: line.split(',') +Out[]: ['Rossum', ' Guido', ' 54', + ' 46', ' 55'] + \end{lstlisting} \end{frame} +\begin{frame}[fragile] + \frametitle{Functions: default arguments \ldots} + \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 -%% \begin{frame} -%% \frametitle{Is this new?} -%% \begin{center} -%% We have moved from: -%% \end{center} -%% \begin{columns} -%% \column{} -%% \hspace*{-1in} -%% \includegraphics[width=1.75in,height=1.75in, interpolate=true]{data/3832} -%% \column{}\hspace*{-0.25in} -%% To -%% \column{} -%% \hspace*{-1in} -%% \includegraphics[width=1.75in, height=1.75in, interpolate=true]{data/torus} -%% \end{columns} -%% \end{frame} +ask_ok('?') +ask_ok('?', '[Y/N]') + \end{lstlisting} +\end{frame} -\begin{frame} - \frametitle{3D visualization} - \Large - \begin{center} - Harder but important - \end{center} +\subsection{Keyword arguments} +\begin{frame}[fragile] + \frametitle{Functions: Keyword arguments} +We have seen the following + \begin{lstlisting} +In []: legend(['sin(2y)'], + loc='center') +In []: plot(y, sin(y), 'g', + linewidth=2) +In []: annotate('local max', + xy=(1.5, 1)) +In []: pie(science.values(), + labels=science.keys()) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: keyword arguments \ldots} + \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} \end{frame} +\subsection{Built-in functions} \begin{frame} - \frametitle{Is this Graphics?} - \Large - \begin{center} - Visualization is about data! - \end{center} + {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} + +\subsection{Exercises} +\begin{frame}{Problem set 3: Problem 3.1} + Write a function to return the gcd of two numbers. \end{frame} -\begin{frame} - \frametitle{Examples: trajectory in space} - \Large - \begin{center} - \pgfimage[width=2.5in]{MEDIA/m2/mlab/plot3d_ex} - \end{center} +\begin{frame}{Problem 3.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 3.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).} +\inctime{15} +\end{frame} + +\section{Modules} +\begin{frame}[fragile] + \frametitle{\typ{from} \ldots \typ{import} magic} + \begin{lstlisting} +from scipy.interpolate import splrep +from scipy.interpolate import splev + +from scipy.integrate import quad +from scipy.integrate import odeint + +from scipy.optimize import fsolve + \end{lstlisting} +\emphbar{All the above statements import one function into your namespace} \end{frame} -\begin{frame} - \frametitle{Examples: Fire in a room} - \Large - \begin{center} - Demo of data - \end{center} -\inctime{10} +\begin{frame}[fragile] + \frametitle{Running scripts from command line} + \small + \begin{itemize} + \item Start cmd + \item cd to Desktop + \item python sine\_plot.py + \end{itemize} + \pause + \begin{lstlisting} +Traceback (most recent call last): + File "sine_plot.py", line 1, in + x = linspace(-5*pi, 5*pi, 500) +NameError: name 'linspace' is not defined + \end{lstlisting} \end{frame} -\section{Tools available} - -\subsection{mlab} +\begin{frame}[fragile] + \frametitle{Remedy} + \emphbar{Adding what lines to sine\_plot.py makes this program work?} + \begin{lstlisting} +from scipy import * + \end{lstlisting} +\alert{Now run python sine\_plot.py again!} + \pause + \begin{lstlisting} +Traceback (most recent call last): + File "sine_plot.py", line 4, in + plot(x, x, 'b') +NameError: name 'plot' is not defined + \end{lstlisting} +\end{frame} -\begin{frame} - {Overview} - \Large - \begin{itemize} - \item Simple - \item Convenient - \item Full-featured +\begin{frame}[fragile] + \frametitle{Remedy \ldots} + \emphbar{What should we add now?} + \begin{lstlisting} +from pylab import * + \end{lstlisting} +\alert{Now run python sine\_plot.py again!!} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules} + \begin{itemize} + \item The \kwrd{import} keyword ``loads'' a module + \item One can also use: + \begin{lstlisting} +In []: from scipy import * +In []: from scipy import linspace + \end{lstlisting} + \item What is the difference? + \item \alert{Use the former only in interactive mode} \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} -In []:from enthought.mayavi import mlab - \end{lstlisting} - - \vspace*{0.5in} - - \myemph{\Large Try these} - - \vspace*{0.25in} - - \begin{lstlisting} -In []: mlab.test_ -In []: mlab.test_contour3d() -In []: 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} -In []: t = linspace(0, 2*pi, 50) -In []: u = cos(t) * pi -In []: x, y, z = sin(u), cos(u), sin(t) - \end{lstlisting} - \emphbar{\PythonCode{In []: 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{In []: mlab.plot3d(x, y, z, t)}} + \frametitle{Package hierarchies} + \begin{lstlisting} +from scipy.interpolate import splev - 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} -In []: x, y = mgrid[-3:3:100j,-3:3:100j] -In []: z = sin(x*x + y*y) - \end{lstlisting} - - \emphbar{\PythonCode{In []: mlab.surf(x, y, z)}} - - \alert{Assumes the points are rectilinear} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{mgrid} - \begin{lstlisting} -In []: mgrid[0:3,0:3] -Out[]: -array([[[0, 0, 0], - [1, 1, 1], - [2, 2, 2]], - - [[0, 1, 2], - [0, 1, 2], - [0, 1, 2]]]) +from scipy.integrate import quad -In []: mgrid[-1:1:5j] -Out[]: array([-1., -0.5, 0., 0.5, 1.]) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Example} - \begin{lstlisting} -In []: x, y = mgrid[-1:1:5j, -1:1:5j] -In []: z = x*x + y*y - -In []: z -Out[]: -array([[ 2. , 1.25, 1. , 1.25, 2. ], - [ 1.25, 0.5 , 0.25, 0.5 , 1.25], - [ 1. , 0.25, 0. , 0.25, 1. ], - [ 1.25, 0.5 , 0.25, 0.5 , 1.25], - [ 2. , 1.25, 1. , 1.25, 2. ]]) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \myemph{\Large 2D data: \texttt{mlab.mesh}} - \vspace*{0.25in} - - \emphbar{\PythonCode{In []: mlab.mesh(x, y, z)}} - - \alert{Points needn't be regular} - - \vspace*{0.25in} -\begin{lstlisting} -In []: phi, theta = mgrid[0:pi:20j, -... 0:2*pi:20j] -In []: x = sin(phi)*cos(theta) -In []: y = sin(phi)*sin(theta) -In []: z = cos(phi) -In []: mlab.mesh(x, y, z, -... representation= -... 'wireframe') -\end{lstlisting} - +from scipy.optimize import fsolve + \end{lstlisting} \end{frame} \begin{frame}[fragile] + \frametitle{from \ldots import in a conventional way!} + \small + \begin{lstlisting} +from scipy import linspace, pi, sin +from pylab import plot, legend, annotate +from pylab import xlim, ylim - \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} -In []: x, y, z = mgrid[-5:5:64j, -... -5:5:64j, -... -5:5:64j] -In []: mlab.contour3d(x*x*0.5 + y*y + - z*z*2) -\end{lstlisting} +x = linspace(-5*pi, 5*pi, 500) +plot(x, x, 'b') +plot(x, -x, 'b') +plot(x, sin(x), 'g', linewidth=2) +plot(x, x*sin(x), 'r', linewidth=3) +legend(['x', '-x', 'sin(x)', 'xsin(x)']) +annotate('origin', xy = (0, 0)) +xlim(-5*pi, 5*pi) +ylim(-5*pi, 5*pi) + \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} -In []: mlab.test_quiver3d() -\end{lstlisting} - -\emphbar{\PythonCode{obj = mlab.quiver3d(x, y, z, u, v, w)}} -\inctime{20} -\end{frame} - - -\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 all 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} - + \frametitle{from \ldots import in a conventional way!} + \small + \begin{lstlisting} +import scipy +import pylab -\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} - -\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() - +x = scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500) +pylab.plot(x, x, 'b') +pylab.plot(x, -x, 'b') +pylab.plot(x, scipy.sin(x), 'g', linewidth=2) +pylab.plot(x, x*scipy.sin(x), 'r', linewidth=3) +pylab.legend(['x', '-x', 'sin(x)', 'xsin(x)']) +pylab.annotate('origin', xy = (0, 0)) +pylab.xlim(-5*scipy.pi, 5*scipy.pi) +pylab.ylim(-5*scipy.pi, 5*scipy.pi) \end{lstlisting} \end{frame} \begin{frame} - \frametitle{We have covered:} + \frametitle{Modules: Standard library} \begin{itemize} - \item Need of visualization. - \item Using mlab to create 3 D plots. - \item Mayavi Toolkit. + \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} +\inctime{5} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules of special interest} + \begin{description}[matplotlibfor2d] + \item[\typ{pylab}] Easy, interactive, 2D plotting + + \item[\typ{scipy}] arrays, statistics, optimization, integration, linear + algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + + \item[\typ{Mayavi}] Easy, interactive, 3D plotting + \end{description} +\end{frame} + +\section{Objects} +\begin{frame}{Everything is an Object!} + \begin{itemize} + \item \typ{int} + \item \typ{float} + \item \typ{str} + \item \typ{list} + \item \typ{tuple} + \item \typ{string} + \item \typ{dictionary} + \item \typ{function} + \item User defined class is also an object! + \end{itemize} +\end {frame} + +\begin{frame}[fragile] +\frametitle{Using Objects} + \begin{itemize} + \item Creating Objects + \begin{itemize} + \item Initialization + \end{itemize} + \begin{lstlisting} +In []: a = str() + +In []: b = "Hello World" + \end{lstlisting} + \item Object Manipulation + \begin{itemize} + \item Object methods + \item ``.'' operator + \end{itemize} + \begin{lstlisting} +In []: "Hello World".split() +Out[]: ['Hello', 'World'] + \end{lstlisting} \end{itemize} \end{frame} -\end{document} +\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} + \inctime{10} +\end{frame} +\begin{frame} + \frametitle{What did we learn?} + \begin{itemize} + \item Functions: Default and Keyword arguments + \item Modules + \item Objects + \end{itemize} +\end{frame} + +\end{document} \ No newline at end of file diff -r d4ad532525a2 -r c4e25269a86c day2/session4.tex --- a/day2/session4.tex Fri Nov 06 17:56:22 2009 +0530 +++ b/day2/session4.tex Fri Nov 06 18:33:08 2009 +0530 @@ -74,7 +74,7 @@ \newcommand{\tvtk}{\texttt{tvtk}} \newcommand{\mlab}{\texttt{mlab}} -\newcommand{\typ}[1]{\lstinline{#1}} + \newcounter{time} \setcounter{time}{0} \newcommand{\inctime}[1]{\addtocounter{time}{#1}{\vspace*{0.1in}\tiny \thetime\ m}} @@ -95,12 +95,13 @@ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Title page -\title[Python Development]{Python Development} +\title[3D Plotting]{3D data Visualization} \author[FOSSEE] {FOSSEE} \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {1 November, 2009\\Day 2, Session 3} +\date[] {1 November, 2009\\Day 2, Session 5} + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %\pgfdeclareimage[height=0.75cm]{iitblogo}{iitblogo} @@ -109,8 +110,7 @@ \AtBeginSection[] { \begin{frame} - \frametitle{Outline} - \Large + \frametitle{Outline} \tableofcontents[currentsection,currentsubsection] \end{frame} } @@ -140,423 +140,419 @@ \maketitle \end{frame} -\section{Tests: Getting started} -\begin{frame}[fragile] - \frametitle{gcd revisited!} - \begin{itemize} - \item Open gcd.py - \end{itemize} -\begin{lstlisting} - def gcd(a, b): - if a % b == 0: - return b - return gcd(b, a%b) +\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} + - print gcd(15, 65) - print gcd(16, 76) -\end{lstlisting} - \begin{itemize} - \item python gcd.py - \end{itemize} +%% \begin{frame} +%% \frametitle{Is this new?} +%% \begin{center} +%% We have moved from: +%% \end{center} +%% \begin{columns} +%% \column{} +%% \hspace*{-1in} +%% \includegraphics[width=1.75in,height=1.75in, interpolate=true]{data/3832} +%% \column{}\hspace*{-0.25in} +%% To +%% \column{} +%% \hspace*{-1in} +%% \includegraphics[width=1.75in, height=1.75in, interpolate=true]{data/torus} +%% \end{columns} +%% \end{frame} + +\begin{frame} + \frametitle{3D visualization} + \Large + \begin{center} + Harder but important + \end{center} \end{frame} -\begin{frame}[fragile] - \frametitle{Find lcm using our gcd module} - \begin{itemize} - \item Open lcm.py - \item $lcm = \frac{a*b}{gcd(a,b)}$ - \end{itemize} -\begin{lstlisting} - from gcd import gcd - def lcm(a, b): - return (a * b) / gcd(a, b) - - print lcm(14, 56) -\end{lstlisting} - \begin{itemize} - \item python lcm.py - \end{itemize} - \begin{lstlisting} -5 -4 -56 - \end{lstlisting} +\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} -\begin{frame}[fragile] - \frametitle{Writing stand-alone module} -Edit gcd.py file to: -\begin{lstlisting} - def gcd(a, b): - if a % b == 0: - return b - return gcd(b, a%b) +\section{Tools available} + +\subsection{mlab} - if __name__ == "__main__": - print gcd(15, 65) - print gcd(16, 76) -\end{lstlisting} - \begin{itemize} - \item python gcd.py - \item python lcm.py - \end{itemize} +\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{More use of main} - For automating tests. - \begin{lstlisting} -if __name__ == '__main__': - for line in open('numbers.txt'): - numbers = line.split() - x = int(numbers[0]) - y = int(numbers[1]) - result = (int(numbers[2])) - assert gcd(x, y) == result - \end{lstlisting} + \frametitle{Using mlab} + + \begin{lstlisting} +In []:from enthought.mayavi import mlab + \end{lstlisting} + + \vspace*{0.5in} + + \myemph{\Large Try these} + + \vspace*{0.25in} + + \begin{lstlisting} +In []: mlab.test_ +In []: mlab.test_contour3d() +In []: mlab.test_contour3d?? + \end{lstlisting} \end{frame} -\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{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} +\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{Code Layout} - \begin{itemize} - \item Indentation - \item Tabs or Spaces?? - \item Maximum Line Length - \item Blank Lines - \item Encodings - \end{itemize} -\end{frame} + \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{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} + \begin{lstlisting} +In []: t = linspace(0, 2*pi, 50) +In []: u = cos(t) * pi +In []: x, y, z = sin(u), cos(u), sin(t) + \end{lstlisting} + \emphbar{\PythonCode{In []: mlab.points3d(x, y, z)}} \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} + \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{In []: mlab.plot3d(x, y, z, t)}} -\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{5} -\end{frame} - -\section{Debugging} -\subsection{Errors and Exceptions} -\begin{frame}[fragile] - \frametitle{Errors} - \begin{lstlisting} -In []: while True print 'Hello world' - \end{lstlisting} -\pause - \begin{lstlisting} - File "", line 1, in ? - while True print 'Hello world' - ^ -SyntaxError: invalid syntax -\end{lstlisting} + Plots lines between the points + \end{frame} \begin{frame}[fragile] - \frametitle{Exceptions} - \begin{lstlisting} -In []: print spam -\end{lstlisting} -\pause -\begin{lstlisting} -Traceback (most recent call last): - File "", line 1, in -NameError: name 'spam' is not defined -\end{lstlisting} + \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} +In []: x, y = mgrid[-3:3:100j,-3:3:100j] +In []: z = sin(x*x + y*y) + \end{lstlisting} + + \emphbar{\PythonCode{In []: mlab.surf(x, y, z)}} + + \alert{Assumes the points are rectilinear} + \end{frame} \begin{frame}[fragile] - \frametitle{Exceptions} - \begin{lstlisting} -In []: 1 / 0 -\end{lstlisting} -\pause -\begin{lstlisting} -Traceback (most recent call last): - File "", line 1, in -ZeroDivisionError: integer division -or modulo by zero + \frametitle{mgrid} + \begin{lstlisting} +In []: mgrid[0:3,0:3] +Out[]: +array([[[0, 0, 0], + [1, 1, 1], + [2, 2, 2]], + + [[0, 1, 2], + [0, 1, 2], + [0, 1, 2]]]) + +In []: mgrid[-1:1:5j] +Out[]: array([-1., -0.5, 0., 0.5, 1.]) \end{lstlisting} \end{frame} \begin{frame}[fragile] - \frametitle{Handling Exceptions} - Python uses \typ{try} and \typ{except} clause. - %%Revisiting the raw\_input + \frametitle{Example} \begin{lstlisting} -a = raw_input('Enter number(Q to quit):') -try: - num = int(a) - print num -except: - if a == 'Q': - print 'Exiting...' - else: - print 'Wrong input!' - \end{lstlisting} - - -\end{frame} +In []: x, y = mgrid[-1:1:5j, -1:1:5j] +In []: z = x*x + y*y -%% \begin{frame}[fragile] -%% \frametitle{Solving it with \typ{try} and \typ{except}} -%% \vspace{-0.2in} -%% \begin{lstlisting} -%% highest = 0 -%% for record in open('sslc1.txt'): -%% fields = record.split(';') -%% try: -%% total = 0 -%% for score_str in fields[3:8]: -%% score = int(score_str) -%% total += score -%% if total > highest: -%% highest = total -%% except: -%% pass -%% print highest -%% \end{lstlisting} -%% \end{frame} -\subsection{Strategy} -\begin{frame}[fragile] - \frametitle{Debugging effectively} - \begin{itemize} - \item \typ{print} based strategy - \item Process: - \end{itemize} -\begin{center} -\pgfimage[interpolate=true,width=5cm,height=5cm]{DebugginDiagram.png} -\end{center} +In []: z +Out[]: +array([[ 2. , 1.25, 1. , 1.25, 2. ], + [ 1.25, 0.5 , 0.25, 0.5 , 1.25], + [ 1. , 0.25, 0. , 0.25, 1. ], + [ 1.25, 0.5 , 0.25, 0.5 , 1.25], + [ 2. , 1.25, 1. , 1.25, 2. ]]) +\end{lstlisting} \end{frame} \begin{frame}[fragile] - \frametitle{Debugging effectively} - \begin{itemize} - \item Using \typ{\%debug} in IPython - \end{itemize} + \myemph{\Large 2D data: \texttt{mlab.mesh}} + \vspace*{0.25in} + + \emphbar{\PythonCode{In []: mlab.mesh(x, y, z)}} + + \alert{Points needn't be regular} + + \vspace*{0.25in} +\begin{lstlisting} +In []: phi, theta = mgrid[0:pi:20j, +... 0:2*pi:20j] +In []: x = sin(phi)*cos(theta) +In []: y = sin(phi)*sin(theta) +In []: z = cos(phi) +In []: 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} +In []: x, y, z = mgrid[-5:5:64j, +... -5:5:64j, +... -5:5:64j] +In []: mlab.contour3d(x*x*0.5 + y*y + + z*z*2) +\end{lstlisting} \end{frame} \begin{frame}[fragile] -\frametitle{Debugging in IPython} -\small + + \myemph{\Large 3D vector data: \PythonCode{mlab.quiver3d}} + \vspace*{0.25in} + + \pgfimage[width=2in]{MEDIA/m2/mlab/quiver3d_ex}\\ + \begin{lstlisting} -In []: import mymodule -In []: 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 []: mlab.test_quiver3d() +\end{lstlisting} + +\emphbar{\PythonCode{obj = mlab.quiver3d(x, y, z, u, v, w)}} +\inctime{20} +\end{frame} + + +\subsection{Mayavi2} -In []: %debug -> mymodule.py(2)test() - 0 print spam -ipdb> -\end{lstlisting} -\inctime{15} +\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 all 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} -\subsection{Exercise} -\begin{frame}[fragile] -\frametitle{Debugging: Exercise} -\small -\begin{lstlisting} -science = {} -for record in open('sslc1.txt'): - fields = record.split(';') - region_code = fields[0].strip() +\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} - score_str = fields[6].strip() - score = int(score_str) if score_str != 'AA' - else 0 +\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} - if score > 90: - science[region_code] += 1 - -pie(science.values(), labels=science.keys()) -savefig('science.png') -\end{lstlisting} -\inctime{10} +\begin{frame} + {Exploring the documentation} + \begin{center} + \pgfimage[width=4in]{MEDIA/m2/m2_ug_doc} + \end{center} \end{frame} -%% \begin{frame} -%% \frametitle{Testing} - -%% \begin{itemize} -%% \item Writing tests is really simple! - -%% \item Using nose. - -%% \item Example! -%% \end{itemize} -%% \end{frame} -\section{Test Driven Approach} \begin{frame} - \frametitle{Need for Testing!} - - \begin{itemize} - \item Quality - \item Regression - \item Documentation - \end{itemize} - %% \vspace*{0.25in} - %% \emphbar{It is to assure that section of code is working as it is supposed to work} + \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} -\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} + {Getting hands dirty!} -\begin{frame}[fragile] - \frametitle{Function: palindrome.py} -\begin{lstlisting} -def is_palindrome(input_str): - return input_str == input_str[::-1] -\end{lstlisting} + \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{Test for the palindrome: palindrome.py} -\begin{lstlisting} -def test_function_normal_words(): - input = "noon" - assert is_palindrome(input) == True - -if __name__ == "main'': - test_function_normal_words() -\end{lstlisting} -\end{frame} + \frametitle{Simple solution} -\begin{frame}[fragile] - \frametitle{Running the tests.} -\begin{lstlisting} -$ nosetests palindrome.py -. ----------------------------------------------- -Ran 1 test in 0.001s - -OK -\end{lstlisting} + \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: 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 palindrome.py} \\ - \begin{block}{Task} - Tweak the code to pass this test. - \end{block} + \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} -%\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: -%% \begin{center} -%% $gcd(a,b)=gcd(b,b\%a)$ -%% \end{center} -%% 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} - \frametitle{Summary} -We have coverd: + \frametitle{We have covered:} \begin{itemize} - \item Following and Resolving Error Messages. - \item Exceptions. - \item Handling exceptions - \item Approach for Debugging. - \item Writting and running tests. + \item Need of visualization. + \item Using mlab to create 3 D plots. + \item Mayavi Toolkit. \end{itemize} \end{frame} \end{document} + diff -r d4ad532525a2 -r c4e25269a86c day2/session5.tex --- a/day2/session5.tex Fri Nov 06 17:56:22 2009 +0530 +++ b/day2/session5.tex Fri Nov 06 18:33:08 2009 +0530 @@ -1,33 +1,48 @@ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. +% 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] +\documentclass[compress,14pt]{beamer} +% \documentclass[handout]{beamer} +% \usepackage{pgfpages} +% \pgfpagesuselayout{4 on 1}[a4paper,border, shrink=5mm,landscape] +\usepackage{tikz} +\newcommand{\hyperlinkmovie}{} +%\usepackage{movie15} -% Modified from: generic-ornate-15min-45min.de.tex +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Note that in presentation mode +% \paperwidth 364.19536pt +% \paperheight 273.14662pt +% h/w = 0.888 + + \mode { \usetheme{Warsaw} + %\usetheme{Boadilla} + %\usetheme{default} \useoutertheme{infolines} \setbeamercovered{transparent} } +% To remove navigation symbols +\setbeamertemplate{navigation symbols}{} + +\usepackage{amsmath} \usepackage[english]{babel} \usepackage[latin1]{inputenc} -%\usepackage{times} +\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} @@ -40,50 +55,65 @@ keywordstyle=\color{blue}\bfseries} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros +% 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}} +\newcommand{\typ}[1]{\lstinline{#1}} \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}}} } +\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\vspace*{0.1in}\tiny \thetime\ m}} -%%% 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 -% } +\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[Exercises]{Exercises} +\title[Python Development]{Python Development} \author[FOSSEE] {FOSSEE} \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date[] {1 November, 2009\\Day 2, Session 4} +\date[] {1 November, 2009\\Day 2, Session 3} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} -%\logo{\pgfuseimage{iitmlogo}} +%\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: @@ -95,109 +125,438 @@ \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} - +\AtBeginSection[] +{ + \begin{frame} + \frametitle{Outline} + \tableofcontents[currentsection,currentsubsection] + \end{frame} +} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % DOCUMENT STARTS \begin{document} \begin{frame} - \titlepage + \maketitle +\end{frame} + +\section{Tests: Getting started} +\begin{frame}[fragile] + \frametitle{gcd revisited!} + \begin{itemize} + \item Open gcd.py + \end{itemize} +\begin{lstlisting} + def gcd(a, b): + if a % b == 0: + return b + return gcd(b, a%b) + + print gcd(15, 65) + print gcd(16, 76) +\end{lstlisting} + \begin{itemize} + \item python gcd.py + \end{itemize} \end{frame} -\begin{frame}{Problem 1.1} - The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. \\For example: -\center{aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.}\\ - Write a function that returns the aliquot number of a given number. +\begin{frame}[fragile] + \frametitle{Find lcm using our gcd module} + \begin{itemize} + \item Open lcm.py + \item $lcm = \frac{a*b}{gcd(a,b)}$ + \end{itemize} +\begin{lstlisting} + from gcd import gcd + def lcm(a, b): + return (a * b) / gcd(a, b) + + print lcm(14, 56) +\end{lstlisting} + \begin{itemize} + \item python lcm.py + \end{itemize} + \begin{lstlisting} +5 +4 +56 + \end{lstlisting} \end{frame} -\begin{frame}{Problem 1.2} - Pair of numbers (a, b) is said to be \alert{amicable} if aliquot number of a is b and aliquot number of b is a.\\ - Example: \texttt{220, 284}\\ - Write a program that prints all four digit amicable pairs. - -\inctime{20} +\begin{frame}[fragile] + \frametitle{Writing stand-alone module} +Edit gcd.py file to: +\begin{lstlisting} + def gcd(a, b): + if a % b == 0: + return b + return gcd(b, a%b) + + if __name__ == "__main__": + print gcd(15, 65) + print gcd(16, 76) +\end{lstlisting} + \begin{itemize} + \item python gcd.py + \item python lcm.py + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More use of main} + For automating tests. + \begin{lstlisting} +if __name__ == '__main__': + for line in open('numbers.txt'): + numbers = line.split() + x = int(numbers[0]) + y = int(numbers[1]) + result = (int(numbers[2])) + assert gcd(x, y) == result + \end{lstlisting} +\end{frame} + +\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}{Problem 2} -%% Given an empty chessboard and one Bishop placed in any s%quare, say (r, c), generate the list of all squares the Bi%shop could move to. - -%% \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{Problem Set 2} - 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} -\inctime{10} + \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{5} \end{frame} -\begin{frame} - \frametitle{Problem Set 3} - \begin{description} - \item[3.1] Count word frequencies in a file. -\end{description} -\inctime{5} +\section{Debugging} +\subsection{Errors and Exceptions} +\begin{frame}[fragile] + \frametitle{Errors} + \begin{lstlisting} +In []: 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} +In []: 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} +In []: 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} \begin{frame}[fragile] - \frametitle{Problem set 4} - Central difference - \begin{equation*} - \frac{sin(x+h)-sin(x-h)}{2h} - \end{equation*} + \frametitle{Handling Exceptions} + Python uses \typ{try} and \typ{except} clause. + %%Revisiting the raw\_input \begin{lstlisting} - In []: x = linspace(0, 2*pi, 100) - In []: y = sin(x) - In []: deltax = x[1] - x[0] +a = raw_input('Enter number(Q to quit):') +try: + num = int(a) + print num +except: + if a == 'Q': + print 'Exiting...' + else: + print 'Wrong input!' \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{Solving it with \typ{try} and \typ{except}} +%% \vspace{-0.2in} +%% \begin{lstlisting} +%% highest = 0 +%% for record in open('sslc1.txt'): +%% fields = record.split(';') +%% try: +%% total = 0 +%% for score_str in fields[3:8]: +%% score = int(score_str) +%% total += score +%% if total > highest: +%% highest = total +%% except: +%% pass +%% print highest +%% \end{lstlisting} +%% \end{frame} +\subsection{Strategy} +\begin{frame}[fragile] + \frametitle{Debugging effectively} + \begin{itemize} + \item \typ{print} based strategy + \item Process: + \end{itemize} +\begin{center} +\pgfimage[interpolate=true,width=5cm,height=5cm]{DebugginDiagram.png} +\end{center} \end{frame} -\begin{frame} - \frametitle{Problem Set 5} - \begin{itemize} - \item[5.1] Write a function that plots any regular n-gon given \typ{n}. - \item[5.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} +\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 []: import mymodule +In []: 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 []: %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} +science = {} + +for record in open('sslc1.txt'): + fields = record.split(';') + region_code = fields[0].strip() + + score_str = fields[6].strip() + score = int(score_str) if score_str != 'AA' + else 0 + + if score > 90: + science[region_code] += 1 + +pie(science.values(), labels=science.keys()) +savefig('science.png') +\end{lstlisting} +\inctime{10} \end{frame} -\begin{frame}[fragile] -\frametitle{Problem Set 5} - \begin{columns} - \column{0.6\textwidth} - \small{ +%% \begin{frame} +%% \frametitle{Testing} + +%% \begin{itemize} +%% \item Writing tests is really simple! + +%% \item Using nose. + +%% \item Example! +%% \end{itemize} +%% \end{frame} + +\section{Test Driven Approach} +\begin{frame} + \frametitle{Need for Testing!} + \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} + \item Quality + \item Regression + \item Documentation + \end{itemize} + %% \vspace*{0.25in} + %% \emphbar{It is to assure that section of code is working as it is supposed to work} +\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} +def test_function_normal_words(): + input = "noon" + assert is_palindrome(input) == True + +if __name__ == "main'': + test_function_normal_words() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Running the tests.} +\begin{lstlisting} +$ nosetests palindrome.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 palindrome.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: +%% \begin{center} +%% $gcd(a,b)=gcd(b,b\%a)$ +%% \end{center} +%% 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} - \frametitle{Problem Set 5.3} - 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} + \frametitle{Summary} +We have coverd: + \begin{itemize} + \item Following and Resolving Error Messages. + \item Exceptions. + \item Handling exceptions + \item Approach for Debugging. + \item Writting and running tests. + \end{itemize} \end{frame} \end{document} diff -r d4ad532525a2 -r c4e25269a86c day2/session6.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/day2/session6.tex Fri Nov 06 18:33:08 2009 +0530 @@ -0,0 +1,203 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%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{infolines} + \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[Exercises]{Exercises} + +\author[FOSSEE] {FOSSEE} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {1 November, 2009\\Day 2, 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: +\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}{Problem 1.1} + The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. \\For example: +\center{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 1.2} + Pair of numbers (a, b) is said to be \alert{amicable} if aliquot number of a is b and aliquot number of b is a.\\ + Example: \texttt{220, 284}\\ + Write a program that prints all four digit amicable pairs. + +\inctime{20} +\end{frame} + +%% \begin{frame}{Problem 2} +%% Given an empty chessboard and one Bishop placed in any s%quare, say (r, c), generate the list of all squares the Bi%shop could move to. + +%% \end{frame} + +\begin{frame}[fragile] + \frametitle{Problem Set 2} + 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} +\inctime{10} +\end{frame} + +\begin{frame} + \frametitle{Problem Set 3} + \begin{description} + \item[3.1] Count word frequencies in a file. +\end{description} +\inctime{5} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem set 4} + Central difference + \begin{equation*} + \frac{sin(x+h)-sin(x-h)}{2h} + \end{equation*} + \begin{lstlisting} + In []: x = linspace(0, 2*pi, 100) + In []: y = sin(x) + In []: 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} + \frametitle{Problem Set 5} + \begin{itemize} + \item[5.1] Write a function that plots any regular n-gon given \typ{n}. + \item[5.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 5} + \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} + \frametitle{Problem Set 5.3} + 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} + +\end{document}