# HG changeset patch # User bhanu # Date 1289422735 -19800 # Node ID 68813d8d80fbf485c4b9686473bf36b2b9462b63 # Parent be96dc6c9743566ab5abe45c8760a07079c9d9e4# Parent c61ed190af5e22f293ec503397b4e0ea37492e43 Merging Heads diff -r be96dc6c9743 -r 68813d8d80fb #symbolics.rst# --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/#symbolics.rst# Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,343 @@ +Symbolics with Sage +------------------- + +Hello friends and welcome to this tutorial on symbolics with sage. + + +.. #[Madhu: Sounds more or less like an ad!] + +{{{ Part of Notebook with title }}} + +.. #[Madhu: Please make your instructions, instructional. While + recording if I have to read this, think what you are actually + meaning it will take a lot of time] + +We would be using simple mathematical functions on the sage notebook +for this tutorial. + +.. #[Madhu: What is this line doing here. I don't see much use of it] + +During the course of the tutorial we will learn + +{{{ Part of Notebook with outline }}} + +To define symbolic expressions in sage. Use built-in costants and +function. Integration, differentiation using sage. Defining +matrices. Defining Symbolic functions. Simplifying and solving +symbolic expressions and functions. + +.. #[Nishanth]: The formatting is all messed up + First fix the formatting and compile the rst + The I shall review +.. #[Madhu: Please make the above items full english sentences, not + the slides like points. The person recording should be able to + read your script as is. It can read something like "we will learn + how to define symbolic expressions in Sage, using built-in ..."] + +Using sage we can perform mathematical operations on symbols. + +.. #[Madhu: Same mistake with period symbols! Please get the + punctuation right. Also you may have to rephrase the above + sentence as "We can use Sage to perform sybmolic mathematical + operations" or such] + +On the sage notebook type:: + + sin(y) + +It raises a name error saying that y is not defined. But in sage we +can declare y as a symbol using var function. + +.. #[Madhu: But is not required] +:: + var('y') + +Now if you type:: + + sin(y) + + sage simply returns the expression . + +.. #[Madhu: Why is this line indented? Also full stop. When will you + learn? Yes we can correct you. But corrections are for you to + learn. If you don't learn from your mistakes, I don't know what + to say] + +thus now sage treats sin(y) as a symbolic expression . You can use +this to do a lot of symbolic maths using sage's built-in constants and +expressions . + +.. #[Madhu: "Thus now"? It sounds like Dus and Nou, i.e 10 and 9 in + Hindi! Full stop again. "a lot" doesn't mean anything until you + quantify it or give examples.] + +Try out + +.. #[Madhu: "So let us try" sounds better] + :: + + var('x,alpha,y,beta') x^2/alpha^2+y^2/beta^2 + +Similarly , we can define many algebraic and trigonometric expressions +using sage . + +.. #[Madhu: comma again. Show some more examples?] + + +Sage also provides a few built-in constants which are commonly used in +mathematics . + +example : pi,e,oo , Function n gives the numerical values of all these + constants. + +.. #[Madhu: This doesn't sound like scripts. How will I read this + while recording. Also if I were recording I would have read your + third constant as Oh-Oh i.e. double O. It took me at least 30 + seconds to figure out it is infinity] + +For instance:: + + n(e) + + 2.71828182845905 + +gives numerical value of e. + +If you look into the documentation of n by doing + +.. #[Madhu: "documentation of the function "n"?] + +:: + n( + +You will see what all arguments it can take etc .. It will be very +helpful if you look at the documentation of all functions introduced + +.. #[Madhu: What does etc .. mean in a script?] + +Also we can define the no of digits we wish to use in the numerical +value . For this we have to pass an argument digits. Type + +.. #[Madhu: "no of digits"? Also "We wish to obtain" than "we wish to + use"?] +:: + + n(pi, digits = 10) + +Apart from the constants sage also has a lot of builtin functions like +sin,cos,sinh,cosh,log,factorial,gamma,exp,arcsin,arccos,arctan etc ... +lets try some out on the sage notebook. + +.. #[Madhu: Here "a lot" makes sense] +:: + + sin(pi/2) + + arctan(oo) + + log(e,e) + + +Given that we have defined variables like x,y etc .. , We can define +an arbitrary function with desired name in the following way.:: + + var('x') function( {{{ Just to show the documentation + extend this line }}} function('f',x) + +.. #[Madhu: What will the person recording show in the documentation + without a script for it? Please don't assume recorder can cook up + things while recording. It is impractical] + +Here f is the name of the function and x is the independent variable . +Now we can define f(x) to be :: + + f(x) = x/2 + sin(x) + +Evaluating this function f for the value x=pi returns pi/2.:: + + f(pi) + +We can also define functions that are not continuous but defined +piecewise. We will be using a function which is a parabola between 0 +to 1 and a constant from 1 to 2 . type the following as given on the +screen + +.. #[Madhu: Instead of "We will be using ..." how about "Let us define + a function ..."] +:: + + + var('x') h(x)=x^2 g(x)=1 f=Piecewise( {{{ Just to show the + documentation extend this line }}} + f=Piecewise([[(0,1),h(x)],[(1,2),g(x)]],x) f + +Checking f at 0.4, 1.4 and 3 :: f(0.4) f(1.4) f(3) + +.. #[Madhu: Again this doesn't sound like a script] + +for f(3) it raises a value not defined in domain error . + + +Apart from operations on expressions and functions one can also use +them for series . + +.. #[Madhu: I am not able to understand this line. "Use them as +.. series". Use what as series?] + +We first define a function f(n) in the way discussed above.:: + + var('n') function('f', n) + +.. #[Madhu: Shouldn't this be on 2 separate lines?] + +To sum the function for a range of discrete values of n, we use the +sage function sum. + +For a convergent series , f(n)=1/n^2 we can say :: + + var('n') function('f', n) + + f(n) = 1/n^2 + + sum(f(n), n, 1, oo) + +For the famous Madhava series :: var('n') function('f', n) + +.. #[Madhu: What is this? your double colon says it must be code block + but where is the indentation and other things. How will the + recorder know about it?] + + f(n) = (-1)^(n-1)*1/(2*n - 1) + +This series converges to pi/4. It was used by ancient Indians to +interpret pi. + +.. #[Madhu: I am losing the context. Please add something to bring + this thing to the context] + +For a divergent series, sum would raise a an error 'Sum is +divergent' :: + + var('n') + function('f', n) + f(n) = 1/n sum(f(n), n,1, oo) + + + + +We can perform simple calculus operation using sage + +.. #[Madhu: When you switch to irrelevant topics make sure you use + some connectors in English like "Moving on let us see how to + perform simple calculus operations using Sage" or something like + that] +For example lets try an expression first :: + + diff(x**2+sin(x),x) 2x+cos(x) + +The diff function differentiates an expression or a function . Its +first argument is expression or function and second argument is the +independent variable . + +.. #[Madhu: Full stop, Full stop, Full stop] + +We have already tried an expression now lets try a function :: + + f=exp(x^2)+arcsin(x) diff(f(x),x) + +To get a higher order differentiation we need to add an extra argument +for order :: + + diff( diff(f(x),x,3) + +.. #[Madhu: Please try to be more explicit saying third argument] + +in this case it is 3. + + +Just like differentiation of expression you can also integrate them :: + + x = var('x') s = integral(1/(1 + (tan(x))**2),x) s + +.. #[Madhu: Two separate lines.] + +To find the factors of an expression use the "factor" function + +.. #[Madhu: See the diff] + +:: + factor( y = (x^100 - x^70)*(cos(x)^2 + cos(x)^2*tan(x)^2) f = + factor(y) + +One can also simplify complicated expression using sage :: + f.simplify_full() + +This simplifies the expression fully . You can also do simplification +of just the algebraic part and the trigonometric part :: + + f.simplify_exp() f.simplify_trig() + +.. #[Madhu: Separate lines?] + +One can also find roots of an equation by using find_root function:: + + phi = var('phi') find_root(cos(phi)==sin(phi),0,pi/2) + +.. #[Madhu: Separate lines?] + +Lets substitute this solution into the equation and see we were +correct :: + + var('phi') f(phi)=cos(phi)-sin(phi) + root=find_root(f(phi)==0,0,pi/2) f.substitute(phi=root) + +.. #[Madhu: Separate lines?] + +as we can see the solution is almost equal to zero . + +.. #[Madhu: So what?] + +We can also define symbolic matrices :: + + + + var('a,b,c,d') A=matrix([[a,1,0],[0,b,0],[0,c,d]]) A + +.. #[Madhu: Why don't you break the lines?] + +Now lets do some of the matrix operations on this matrix + +.. #[Madhu: Why don't you break the lines? Also how do you connect + this up? Use some transformation keywords in English] +:: + A.det() A.inverse() + +.. #[Madhu: Why don't you break the lines?] + +You can do :: + + A. + +To see what all operations are available + +.. #[Madhu: Sounds very abrupt] + +{{{ Part of the notebook with summary }}} + +So in this tutorial we learnt how to + + +We learnt about defining symbolic expression and functions . +And some built-in constants and functions . +Getting value of built-in constants using n function. +Using Tab to see the documentation. +Also we learnt how to sum a series using sum function. +diff() and integrate() for calculus operations . +Finding roots , factors and simplifying expression using find_root(), +factor() , simplify_full, simplify_exp , simplify_trig . +Substituting values in expression using substitute function. +And finally creating symbolic matrices and performing operation on them . + +.. #[Madhu: See what Nishanth is doing. He has written this as + points. So easy to read out while recording. You may want to + reorganize like that] diff -r be96dc6c9743 -r 68813d8d80fb accessing-pieces-arrays/script.rst --- a/accessing-pieces-arrays/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/accessing-pieces-arrays/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -62,6 +62,8 @@ Pause the video here and make sure you have the arrays A and C, typed in correctly. +{{{ Pause the recording and type the arrays A,C }}} + Let us begin with the most elementary thing, accessing individual elements. Also, let us first do it with the one-dimensional array A, and then do the same thing with the two-dimensional array. @@ -72,6 +74,8 @@ A[2] +A of 2, note that we are using square brackets. + Like lists, indexing starts from 0 in arrays, too. So, 34, the third element has the index 2. @@ -80,6 +84,8 @@ C[2, 3] +C of 2,3. + 34 is in the third row and the fourth column, and since indexing begins from zero, the row index is 2 and column index is 3. diff -r be96dc6c9743 -r 68813d8d80fb accessing-pieces-arrays/slides.org.orig --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/accessing-pieces-arrays/slides.org.orig Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,123 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Antibes}\usecolortheme{lily}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Accessing parts of arrays +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Manipulating one and multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slicing and striding on arrays to access chunks + - Read images into arrays and manipulations +* Sample Arrays + #+begin_src python + In []: A = array([12, 23, 34, 45, 56]) + + In []: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) + + #+end_src +* Question 1 + Change the last column of ~C~ to zeroes. +* Solution 1 + #+begin_src python + In []: C[:, -1] = 0 + #+end_src +* Question 2 + Change ~A~ to ~[11, 12, 13, 14, 15]~. +* Solution 2 + #+begin_src python + In []: A[:] = [11, 12, 13, 14, 15] + #+end_src +* squares.png + #+begin_latex + \begin{center} + \includegraphics[scale=0.6]{squares} + \end{center} + #+end_latex +* Question 3 + - obtain ~[22, 23]~ from ~C~. + - obtain ~[11, 21, 31, 41]~ from ~C~. + - obtain ~[21, 31, 41, 0]~. +* Solution 3 + #+begin_src python + In []: C[1, 1:3] + In []: C[0:4, 0] + In []: C[1:5, 0] + #+end_src +* Question 4 + Obtain ~[[23, 24], [33, -34]]~ from ~C~ +* Solution 4 + #+begin_src python + In []: C[1:3, 2:4] + #+end_src +* Question 5 + Obtain the square in the center of the image +* Solution 5 + #+begin_src python + In []: imshow(I[75:225, 75:225]) + #+end_src +* Question 6 + Obtain the following + #+begin_src python + [[12, 0], [42, 0]] + [[12, 13, 14], [0, 0, 0]] + #+end_src + +* Solution 6 + #+begin_src python + In []: C[::3, 1::3] + In []: C[::4, 1:4] + #+end_src +* Summary + You should now be able to -- + - Manipulate single \& multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slice and stride on arrays + - Read images into arrays and manipulate them. +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r be96dc6c9743 -r 68813d8d80fb accessing-pieces-arrays/slides.tex.orig --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/accessing-pieces-arrays/slides.tex.orig Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,199 @@ +% Created 2010-11-03 Wed 15:37 +\documentclass[presentation]{beamer} +\usetheme{Antibes}\usecolortheme{lily}\useoutertheme{infolines}\setbeamercovered{transparent} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{amssymb} +\usepackage{hyperref} +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +\title{Accessing parts of arrays} +\author{FOSSEE} +\date{} + +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Manipulating one and multi dimensional arrays +\item Access and change individual elements +\item Access and change rows and columns +\item Slicing and striding on arrays to access chunks +\item Read images into arrays and manipulations +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Sample Arrays} +\label{sec-2} + +\begin{verbatim} +In []: A = array([12, 23, 34, 45, 56]) + +In []: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-3} + + Change the last column of \texttt{C} to zeroes. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-4} + +\begin{verbatim} +In []: C[:, -1] = 0 +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-5} + + Change \texttt{A} to \texttt{[11, 12, 13, 14, 15]}. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-6} + +\begin{verbatim} +In []: A[:] = [11, 12, 13, 14, 15] +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{squares.png} +\label{sec-7} + + \begin{center} + \includegraphics[scale=0.6]{squares} + \end{center} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-8} + +\begin{itemize} +\item obtain \texttt{[22, 23]} from \texttt{C}. +\item obtain \texttt{[11, 21, 31, 41]} from \texttt{C}. +\item obtain \texttt{[21, 31, 41, 0]}. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 3} +\label{sec-9} + +\begin{verbatim} +In []: C[1, 1:3] +In []: C[0:4, 0] +In []: C[1:5, 0] +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-10} + + Obtain \texttt{[[23, 24], [33, -34]]} from \texttt{C} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 4} +\label{sec-11} + +\begin{verbatim} +In []: C[1:3, 2:4] +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 5} +\label{sec-12} + + Obtain the square in the center of the image +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 5} +\label{sec-13} + +\begin{verbatim} +In []: imshow(I[75:225, 75:225]) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Question 6} +\label{sec-14} + + Obtain the following +\begin{verbatim} +[[12, 0], [42, 0]] +[[12, 13, 14], [0, 0, 0]] +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 6} +\label{sec-15} + +\begin{verbatim} +In []: C[::3, 1::3] +In []: C[::4, 1:4] +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-16} + + You should now be able to -- +\begin{itemize} +\item Manipulate single \& multi dimensional arrays + +\begin{itemize} +\item Access and change individual elements +\item Access and change rows and columns +\item Slice and stride on arrays +\end{itemize} + +\item Read images into arrays and manipulate them. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-17} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r be96dc6c9743 -r 68813d8d80fb additional_ipython/questions.rst --- a/additional_ipython/questions.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/additional_ipython/questions.rst Thu Nov 11 02:28:55 2010 +0530 @@ -20,6 +20,8 @@ Answer: 21 +.. #[Amit: I really don't get the question below] + 3. is ``%hist`` considered as a command a. True @@ -45,8 +47,10 @@ Answer: raises an error - 6. How many commands are displayed when lot of coomands were typed and + 6. How many commands are displayed when lot of commands were typed and ``%hist`` is used. +.. #[Amit: Ok something wrong with the question. +.. Recommend : What is the default maximum number of commands %hist can show ] a. 20 #. 10 @@ -82,7 +86,9 @@ #. 2 5 7 1 #. 1 2 5 7 - 10. What happens when ``%save filepath line_numbers`` is used and a file + Answer: a + +10. What happens when ``%save filepath line_numbers`` is used and a file already exists in that path. a. It is overwritten @@ -116,3 +122,13 @@ #. Does nothing Answer: increments the value of x by 1 + + +Long Answer questions : +----------------------- + +1. Question 1 +2. Question 2 + +.. #[Amit: I think long answer questions for this script are +.. not possible. Please add if someone comes up with any] diff -r be96dc6c9743 -r 68813d8d80fb additional_ipython/script.rst --- a/additional_ipython/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/additional_ipython/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -39,7 +39,7 @@ on the terminal -{{{ shit to terminal and type ipython -pylab }}} +{{{ shift to terminal and type ipython -pylab }}} We shall first make a plot and then view the history and save it. :: @@ -66,14 +66,14 @@ command has a number in front, to specify in which order and when it was typed. Please note that there is a % sign before the hist command. This implies that -%hist is a command that is specific to IPython and not available in vannila +%hist is a command that is specific to IPython and not available in the vannila Python interpreter. These type of commands are called as magic commands. Also note that, the =%hist= itself is a command and is displayed as the most -recent command. This implies that anything we type in is stored as history, +recent command. We should not that anything we type in is stored as history, irrespective of whether it is command or an error or IPython magic command. -If we want only the recent 5 to be displayed, we pass the number as an argument +If we want only the recent 5 commands to be displayed, we pass the number as an argument to =%hist= command. Hence :: @@ -99,8 +99,7 @@ Now that we have the history, we would like to save the required line of code from history. This is possible by using the =%save= command. -Before we do that, let us first look at history and identify what lines of code -we require.Type +Before we do that, let us first look at history and identify what lines of code we require.Type :: %hist @@ -109,7 +108,7 @@ {{{ point to the lines }}} The first command is linspace. But second command is a command that gave us an -error. Hence we do not need seconf. The commands from third to sixth are +error. Hence we do not need second command. The commands from third to sixth are required. The seventh command although is correct, we do not need it since we are setting the title correctly in the eigthth command. @@ -154,7 +153,7 @@ %run -i /home/fossee/plot_script.py -The script runs but we do not see the plot. This happens because we are running +The script runs but we do not see the plot. This happens because when we are running a script and we are not in interactive mode anymore. Hence on your terminal type @@ -169,6 +168,7 @@ %% 3 %% Use %hist and %save and create a script that has show in it and run it to produce and show the plot. + {{{ continue from paused state }}} We first look at the history using @@ -181,6 +181,7 @@ %save /home/fossee/show_included.py 1 3-6 8 10 13 %run -i /home/fossee/show_included.py + show() We get the desired plot. @@ -195,7 +196,7 @@ {{{ continue from paused state }}} -We see that it raises nameerror saying the name linspace is not found. +We see that it raises NameError saying that the name linspace is not found. {{{ Show summary slide }}} @@ -209,9 +210,9 @@ {{{ Show the "sponsored by FOSSEE" slide }}} -#[Nishanth]: Will add this line after all of us fix on one. + This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India Hope you have enjoyed and found it useful. -Thank you! +Thank You! diff -r be96dc6c9743 -r 68813d8d80fb advanced-features-functions/script.rst --- a/advanced-features-functions/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/advanced-features-functions/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -170,7 +170,8 @@ welcome() -Let us now learn what keyword arguments are. +Let us now learn what keyword arguments or named arguments are. We +shall refer to them as keyword arguments, henceforth. {{{ show a slide with examples using keyword arguments. }}} @@ -186,14 +187,6 @@ pie(science.values(), labels = science.keys()) -.. #[[Anoop: I think it will better to introduce keyword arguments as - keyword/named arguments, as the keyword term was quite confusing - for me, so can be for someone who already know certain - jargon's/concepts, also it would be good to tell them that these - are different from keywords in programming languages, explicit is - better than implicit, and probably you could also tell them that - from now on we will refer to it as just keyword arguments]] - When you are calling functions in Python, you don't need to remember the order in which to pass the arguments. Instead, you can use the name of the argument to pass it a value. This slide shows a few @@ -250,7 +243,6 @@ .. #[punch: Need to decide, exactly what to put here. Reviewer comments .. welcome.] - {{{ switch to slide showing classes of functions in pylab, scipy }}} .. #[[Anoop: slide missing]] diff -r be96dc6c9743 -r 68813d8d80fb basic-data-type/questions.rst --- a/basic-data-type/questions.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/basic-data-type/questions.rst Thu Nov 11 02:28:55 2010 +0530 @@ -8,32 +8,72 @@ 1. How large can an integer in Python be? - Any Size. + Answer: Any Size. -2. How do you define a complex number in Python? +#. How do you define a complex number in Python? Using the following notation. [Real part] + [Imaginary part] j example :: - c= 3.2 + 4.6j + Answer: c= 3.2 + 4.6j -3. Look at the following piece of code :: +#. Look at the following piece of code :: In []: f or t Out[]:True What can you comment about the data type of f and t ? -4. One major diffence between tuples and lists? +#. One major diffence between tuples and lists? - Tuples are immutable while lists are not. + Answer: Tuples are immutable while lists are not. + + -5. Look at the following sequence :: +#. Put the following string in a variable quotation. + "God doesn't play dice" -Albert Einstein + + quotation='''"God doesn't play dice" -Albert Einstein''' + +#. Given a tuple :: + + tup=(7,4,2,1,3,6,5,8) + tup[-2] + + 5 + +.. #[Puneeth: ``Answer: Any size.``. Demarcate the answer from the +.. question.] + +#. What is the syntax for checking containership in Python?:: + + element in sequence + 'l' in "Hello" + True + +#. Split this string on whitespaces? :: + + string="Split this string on whitespaces?" + + string.split() + +#. What is the answer of 5/2 and 5.0/2 . If yes , why. + + Yes, There is a difference. + Because one is integer division and other is float division. + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + + +1. Look at the following sequence :: In []:t=true NameError: name 'true' is not defined @@ -46,49 +86,9 @@ gives a NameError. -6. Put the following string in a variable quotation. - "God doesn't play dice" -Albert Einstein - quotation='''"God doesn't play dice" -Albert Einstein''' - -7. Given a tuple :: - - tup=(7,4,2,1,3,6,5,8) - tup[-2] - - 5 - -.. #[Puneeth: ``Answer: Any size.``. Demarcate the answer from the -.. question.] - -8. What is the syntax for checking containership in Python?:: - - element in sequence - 'l' in "Hello" - True - -9. Split this string on whitespaces? :: - - string="Split this string on whitespaces?" - - string.split() - -10. What is the answer of 5/2 and 5.0/2 . If yes , why. - - Yes, There is a difference. - Because one is integer division and other is float division. - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Given two lists for example, - list1=[1,2,3,4] and list2=[1,2,3,4,5,6,7] write a program to remove one list from the other. - -.. #[Puneeth: dependency LOs?] - -#. Write a program to check if a string is palindrome? +#. Convert the string "I,learnt,python,through,spoken,tutorial" + to "I,learnt through spoken tutorial" .. #[Puneeth: comparison has not been taught, has it? does this depend .. on any other LO?] diff -r be96dc6c9743 -r 68813d8d80fb basic-data-type/script.rst --- a/basic-data-type/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/basic-data-type/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -16,8 +16,6 @@ External Reviewer : Checklist OK? : [2010-10-05] -.. #[Puneeth: Fill in pre-requisites.] - Hello friends and welcome to the tutorial on Basic Data types and operators in Python. @@ -27,7 +25,7 @@ In this tutorial, we shall look at - * Datatypes in Python +* Datatypes in Python * Numbers * Boolean * Sequence @@ -35,19 +33,15 @@ * Arithmetic Operators * Boolean Operators -* Manipulating Sequence datatypes - -.. #[Puneeth: Use double colon only for code blocks.] -.. #[Puneeth: include more details in the outline.] - -with a little hands-on on how they can be applied to the different data types. - - +* Python Sequence Data types + * list + * string + * tuple First we will explore python data structures in the domain of numbers. There are three built-in data types in python to represent numbers. -{{{ A slide to make a memory note of this }}} +{{{ A slide to make a memory note of the different datatypes }}} These are: @@ -55,12 +49,6 @@ * float * complex -.. #[Puneeth: Changed to int, float and complex.] - -.. #[Puneeth: Loss of consistency. You talk of built-in data types, but -.. then you were calling them integers, floats and complex. Clean up -.. required.] - Lets first talk about int. :: a = 13 @@ -75,38 +63,21 @@ type(a) -This means that a is a type of int. Being an int data structure in python -means that there are various functions that this variable has to manipulate -it different ways. You can explore these by doing, +This means that a is a type of int. There are lot of functions associated +with the int datatype, to manipulate it in different ways. These can be +explored by doing, :: a. -.. #[Puneeth: Why are we suddenly talking of limits? -.. Something like this would be better. -.. int data-type can hold integers of any size. for example - ] - -*int* datatype can hold integers of any size lets see this by example. +*int* datatype can hold integers of any size lets see this by an example. +:: b = 99999999999999999999 b As you can see even when we put a value of 9 repeated 20 times python did -not complain. However when you asked python to print the number again it -put a capital L at the end. Now if you check the type of this variable b, -:: - - type(b) - - - -The reason for this is that python recognizes large integer numbers by the -data type long. However long type and int type share there functions -and properties. - -.. #[Puneeth: again, the clean-up that I talked of above. Decide if you are -.. talking about the different type of numbers and the datatypes that are -.. used to represent them or if you are talking of the data-types and what -.. kind of numbers they represent. I think you should choose the former.] +not complain. This is because python's int data-type can hold integers of any +size. Let us now look at the float data-type. @@ -115,10 +86,10 @@ p = 3.141592 p -If you notice the value of output of p isn't exactly equal to p. This is -because computer saves floating point values in a specific format. There is -always an aproximationation. This is why we should never rely on equality -of floating point numbers in a program. +If you notice the value of output of ``p`` isn't exactly equal to ``p``. +This is because computer saves floating point values in a specific format. +There is always an approximation. This is why we should never rely on +equality of floating point numbers in a program. The last data type in the list is complex number :: @@ -126,7 +97,7 @@ as simple as that so essentialy its just a combination of two floats the imaginary part being defined by j notation instead of i. Complex numbers -have a lot of functions specific to them. Lets check these :: +have a lot of functions specific to them. Let us look at these :: c. @@ -142,8 +113,25 @@ abs(c) +Following is are exercises that you must do. -{{ Slide for memory aid }} +%% %% Find the absolute value of 3+4j +:: + + abs(3+4j) + +%% %% What is the datatype of number 999999999999999999? Is it +not int? +:: + + Long + Big integers are internally stored in python + as Long datatype. + +Please, pause the video here. Do the exercises and then continue. + + +{{ Slide for showing Boolean datatypes }} Python also has Boolean as a built-in type. @@ -163,10 +151,6 @@ The results are self explanatory. -.. #[Puneeth: Why does booleans bring us to precedence? I don't see the -.. connection. Am I missing something?] - - What if you want to apply one operator before another. Well you can use parenthesis for precedence. @@ -178,8 +162,6 @@ c=True -.. #[Puneeth: Consistency. In[]: is not present at other places.] - To check how precedence changes with parenthesis, we will try two expressions and their evaluation. @@ -199,14 +181,12 @@ Let's now look at some operators available in Python to manipulate these data types. -.. #[Puneeth: A mention of other operators would be good? Starting -.. with % and ** is a bit weird.] - Python uses '+' for addition :: 23 + 74 '-' for subtraction :: + 23 - 56 '*' for multiplication :: @@ -216,8 +196,16 @@ '/' for division :: 384/16 + 8/3 + 8.0/3 - '%' for modulo operation :: +When we did 8/3 the first case results in am integer +output as both the operands are integer however when +8.0/3 is used the answer is float as one of the operands is +float. + + +'%' for modulo operation :: 87 % 6 @@ -245,13 +233,27 @@ a=a/23 +Following is are exercises that you must do. + +%% %% Using python find sqaure root of 3? + +%% %% Is 3**1/2 and 3**0.5 same + +Please, pause the video here. Do the exercises and then continue. + +:: + + 3**0.5 + +:: + No,One gives an int answer and the other float + + Lets now discuss sequence data types in Python. Sequence data types are those in which elements are kept in a sequential order and all the -elements accessed using index numbers. +elements are accessed using index numbers. -.. #[Puneeth: fix the last sentence - it sounds incomplete] - -{{{ slide for memory aid }}} +{{{ slide introducing sequence datatype }}} The sequence datatypes in Python are :: @@ -277,8 +279,6 @@ var_list = [1, 1.2, [1,2]] var_list -.. #[Puneeth: some continuity, when jumping to strings?] - Lets look at another sequence data type, strings type :: @@ -288,7 +288,7 @@ greeting_string is now a string variable with the value "hello" -{{{ Memory Aid Slide }}} +{{{ All the different types of strings shown }}} Python strings can actually be defined in three different ways :: @@ -296,12 +296,8 @@ l="Let's see how to include a single quote" m='''"Let's see how to include both"''' -.. #[Puneeth: Contain's? That's not a word!] - As you can see, single quotes are used as delimiters usually. -.. #[Puneeth: Thus?] - When a string contains a single quote, double quotes are used as delimiters. When a string quote contains both single and double quotes, triple quotes are used as delimiters. @@ -365,17 +361,15 @@ max(num_tuple) min(greeting_string) -Get a sorted list and reversed list using sorted and reversed function :: +Get a sorted list :: sorted(num_list) - reversed(greeting_string) + -As a consequence of there order we can access a group of elements of sequence, -together. This is called slicing and striding. +As a consequence of their order, we can access a group of elements in a +sequence, together. This is called slicing and striding. -.. #[Puneeth: Fix the sentence above. ] - -First Slicing +First lets discuss Slicing, Given a list :: @@ -507,7 +501,31 @@ With this we come to the end of this tutorial . -In this tutorial we have discussed +Following is an (are) exercise(s) that you must do. + + + +%% %% Check if 3 is an element of the list [1,7,5,3,4]. In case +it is change it to 21. +:: + l=[1,7,5,3,4] + 3 in l + l[3]=21 + l + +%% %% Convert the string "Elizabeth is queen of england" to +"Elizabeth is queen" +:: + + s="Elizabeth is queen of england" + stemp=s.split() + ' '.join(stemp[:3]) + +Please, pause the video here. Do the exercise(s) and then continue. + + +This brings us to the end of the tutorial. In this tutorial we have +discussed 1. Number Datatypes , integer,float and complex 2. Boolean and datatype and operators @@ -517,16 +535,6 @@ 6. Finding length , sorting and reversing operations on sequences. 7. Immutability. - - - -.. #[Nishanth]: string to list is fine. But list to string can be left for - string manipulations. Just say it requires some string - manipulations and leave it there. - -.. #[Nishanth]: Where is the summary - There are no exercises in the script - {{{ Show the "sponsored by FOSSEE" slide }}} This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India diff -r be96dc6c9743 -r 68813d8d80fb basic-data-type/slides.org --- a/basic-data-type/slides.org Mon Nov 08 02:12:28 2010 +0530 +++ b/basic-data-type/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -2,74 +2,157 @@ #+LaTeX_CLASS_OPTIONS: [presentation] #+BEAMER_FRAME_LEVEL: 1 -#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} #+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) #+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC -#+OPTIONS: H:5 num:t toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} #+TITLE: Plotting Data #+AUTHOR: FOSSEE #+DATE: 2010-09-14 Tue -#+EMAIL: info@fossee.in +#+EMAIL: info@fossee.in -# \author[FOSSEE] {FOSSEE} +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:1 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc +#+STARTUP: align fold nodlcheck hidestars oddeven lognotestate -# \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -# \date{} - -* Tutorial Plan +* Outline ** Datatypes in Python +*** Numbers +*** Boolean +*** Sequence ** Operators in Python +*** Arithmetic Operators +*** Boolean Operators +** Python Sequence Datatypes +*** list +*** string +*** tuple * Numbers -** Integers -** Float -** Complex + - int + - float + - complex +* Question 1 + - Find the absolute value of 3+4j +* Solution 1 + #+begin_src python + abs(3+4j) + #+end_src python +* Question 2 + - What is the datatype of number 999999999999999999? Is it +not int? + +* Solution 2 + - Long + - Large integers numbers are internally stored in python as Long + datatype. + * Boolean -** True -** False + #+begin_src python + In []: t=True + In []: f=False + #+end_src + +* Question 3 + - Using python find sqaure root of 3? + +* Solution 3 + + - 3**0.5 + +* Question 4 + - Is 3**1/2 and 3**0.5 same +* Solution 4 + - No,One gives an int answer and the other float * Sequence Data types -** Data in Sequence -** Accessed using Index -*** list -*** String -*** Tuple +** Properties + - Data in Sequence + - Accessed using Index +** Type + - list + - String + - Tuple * All are Strings - -** k='Single quote' -** l="Double quote contain's single quote" -** m='''"Contain's both"''' + #+begin_src python + k = 'Single quote' + l = "Double quote contain's single quote" + m = '''"Contain's both"''' -* Summary -** a=73 -** b=3.14 -** c=3+4j + #+end_src +* Immutabilty Error + #+begin_src python + In []: greeting_string[1]='k' + ------------------------------------------------------- + TypeError Traceback (most recent call last) -* Summary Contd. + /home/fossee/ in () -** t=True -** f=False -** t and f + TypeError: 'str' object does not support item assignment + #+end_src + +* Question 5 + Check if 3 is an element of the list [1,7,5,3,4]. In case it is +change it to 21. -* Summary Contd. -** l= [2,1,4,3] -** s='hello' -** tu=(1,2,3,4) - -* Summary Contd. -** tu[-1] -** s[1:-1] +* Solution 5 + #+begin_src python + l=[1,7,5,3,4] + 3 in l + l[3]=21 + l + #+end_src +* Question 6 + Convert the string ~"Elizabeth is queen of england"~ to ~"Elizabeth is +queen"~ -* Summary Contd. - -** Sorted(l) -** reversed(s) - -* COMMENT -# [Puneeth: Where is the last slide?] -# [Puneeth: Why don't you use the template slides.org?] +* Solution 6 + #+begin_src python + s = "Elizabeth is queen of england" + stemp = s.split() + ' '.join(stemp[:3]) + #+end_src +* Summary + - Number Datatypes -- integer,float and complex + - Boolean and datatype and operators + - Sequence data types -- List, String and Tuple + - Accesing sequence + - Slicing sequences + - Finding length, sorting and reversing operations on sequences + - Immutability +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + + diff -r be96dc6c9743 -r 68813d8d80fb basic-data-type/slides.org.orig --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic-data-type/slides.org.orig Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,158 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Plotting Data +#+AUTHOR: FOSSEE +#+DATE: 2010-09-14 Tue +#+EMAIL: info@fossee.in + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:1 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc +#+STARTUP: align fold nodlcheck hidestars oddeven lognotestate + +* Outline +** Datatypes in Python +*** Numbers +*** Boolean +*** Sequence +** Operators in Python +*** Arithmetic Operators +*** Boolean Operators +** Python Sequence Datatypes +*** list +*** string +*** tuple + +* Numbers + - int + - float + - complex +* Question 1 + - Find the absolute value of 3+4j +* Solution 1 + #+begin_src python + abs(3+4j) + #+end_src python +* Question 2 + - What is the datatype of number 999999999999999999? Is it +not int? + +* Solution 2 + - Long + - Large integers numbers are internally stored in python as Long + datatype. + + +* Boolean + #+begin_src python + In []: t=True + In []: f=False + #+end_src + +* Question 3 + - Using python find sqaure root of 3? + +* Solution 3 + + - 3**0.5 + +* Question 4 + - Is 3**1/2 and 3**0.5 same +* Solution 4 + - No,One gives an int answer and the other float + +* Sequence Data types +** Properties + - Data in Sequence + - Accessed using Index +** Type + - list + - String + - Tuple + +* All are Strings + #+begin_src python + k = 'Single quote' + l = "Double quote contain's single quote" + m = '''"Contain's both"''' + + #+end_src +* Immutabilty Error + #+begin_src python + In []: greeting_string[1]='k' + ------------------------------------------------------- + TypeError Traceback (most recent call last) + + /home/fossee/ in () + + TypeError: 'str' object does not support item assignment + #+end_src + +* Question 5 + Check if 3 is an element of the list [1,7,5,3,4]. In case it is +change it to 21. + +* Solution 5 + #+begin_src python + l=[1,7,5,3,4] + 3 in l + l[3]=21 + l + #+end_src +* Question 6 + Convert the string ~"Elizabeth is queen of england"~ to ~"Elizabeth is +queen"~ + +* Solution 6 + #+begin_src python + s = "Elizabeth is queen of england" + stemp = s.split() + ' '.join(stemp[:3]) + #+end_src +* Summary + - Number Datatypes -- integer,float and complex + - Boolean and datatype and operators + - Sequence data types -- List, String and Tuple + - Accesing sequence + - Slicing sequences + - Finding length, sorting and reversing operations on sequences + - Immutability +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + + + + diff -r be96dc6c9743 -r 68813d8d80fb basic-data-type/slides.tex --- a/basic-data-type/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/basic-data-type/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,21 +1,34 @@ -% Created 2010-10-13 Wed 17:08 +% Created 2010-11-09 Tue 15:26 \documentclass[presentation]{beamer} -\usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} \usepackage[latin1]{inputenc} \usepackage[T1]{fontenc} +\usepackage{fixltx2e} \usepackage{graphicx} \usepackage{longtable} \usepackage{float} \usepackage{wrapfig} \usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} \usepackage{amssymb} \usepackage{hyperref} - +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} \title{Plotting Data } \author{FOSSEE} \date{2010-09-14 Tue} +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} \maketitle @@ -25,134 +38,249 @@ + + + \begin{frame} -\frametitle{Tutorial Plan} +\frametitle{Outline} \label{sec-1} \begin{itemize} -\item Datatypes in Python\\ -\label{sec-1.1}% -\item Operators in Python\\ -\label{sec-1.2}% +\item Datatypes in Python +\label{sec-1_1}% +\begin{itemize} + +\item Numbers\\ +\label{sec-1_1_1}% +\item Boolean\\ +\label{sec-1_1_2}% +\item Sequence\\ +\label{sec-1_1_3}% +\end{itemize} % ends low level + +\item Operators in Python +\label{sec-1_2}% +\begin{itemize} + +\item Arithmetic Operators\\ +\label{sec-1_2_1}% +\item Boolean Operators\\ +\label{sec-1_2_2}% +\end{itemize} % ends low level + +\item Python Sequence Datatypes +\label{sec-1_3}% +\begin{itemize} + +\item list\\ +\label{sec-1_3_1}% +\item string\\ +\label{sec-1_3_2}% +\item tuple\\ +\label{sec-1_3_3}% +\end{itemize} % ends low level \end{itemize} % ends low level \end{frame} \begin{frame} \frametitle{Numbers} \label{sec-2} + \begin{itemize} +\item int +\item float +\item complex +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-3} -\item Integers\\ -\label{sec-2.1}% -\item Float\\ -\label{sec-2.2}% -\item Complex\\ -\label{sec-2.3}% -\end{itemize} % ends low level +\begin{itemize} +\item Find the absolute value of 3+4j +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-4} + +\begin{verbatim} +abs(3+4j) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-5} + +\begin{itemize} +\item What is the datatype of number 999999999999999999? Is it +\end{itemize} + +not int? \end{frame} \begin{frame} +\frametitle{Solution 2} +\label{sec-6} + +\begin{itemize} +\item Long +\item Large integers numbers are internally stored in python as Long + datatype. +\end{itemize} +\end{frame} +\begin{frame}[fragile] \frametitle{Boolean} -\label{sec-3} -\begin{itemize} +\label{sec-7} + +\begin{verbatim} +In []: t=True +In []: f=False +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-8} -\item True\\ -\label{sec-3.1}% -\item False\\ -\label{sec-3.2}% -\end{itemize} % ends low level +\begin{itemize} +\item Using python find sqaure root of 3? +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Solution 3} +\label{sec-9} + + +\begin{itemize} +\item 3**0.5 +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-10} + +\begin{itemize} +\item Is 3**1/2 and 3**0.5 same +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Solution 4} +\label{sec-11} + +\begin{itemize} +\item No,One gives an int answer and the other float +\end{itemize} \end{frame} \begin{frame} \frametitle{Sequence Data types} -\label{sec-4} -\begin{itemize} - -\item Data in Sequence\\ -\label{sec-4.1}% -\item Accessed using Index -\label{sec-4.2}% +\label{sec-12} \begin{itemize} -\item list\\ -\label{sec-4.2.1}% -\item String\\ -\label{sec-4.2.2}% -\item Tuple\\ -\label{sec-4.2.3}% +\item Properties +\label{sec-12_1}% +\begin{itemize} +\item Data in Sequence +\item Accessed using Index +\end{itemize} + + +\item Type +\label{sec-12_2}% +\begin{itemize} +\item list +\item String +\item Tuple +\end{itemize} + + \end{itemize} % ends low level -\end{itemize} % ends low level +\end{frame} +\begin{frame}[fragile] +\frametitle{All are Strings} +\label{sec-13} + +\begin{verbatim} +k = 'Single quote' +l = "Double quote contain's single quote" +m = '''"Contain's both"''' +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Immutabilty Error} +\label{sec-14} + +\begin{verbatim} +In []: greeting_string[1]='k' +------------------------------------------------------- +TypeError Traceback (most recent call last) + +/home/fossee/ in () + +TypeError: 'str' object does not support item assignment +\end{verbatim} \end{frame} \begin{frame} -\frametitle{All are Strings} -\label{sec-5} -\begin{itemize} +\frametitle{Question 5} +\label{sec-15} + + Check if 3 is an element of the list [1,7,5,3,4]. In case it is +change it to 21. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 5} +\label{sec-16} -\item k='Single quote'\\ -\label{sec-5.1}% -\item l="Double quote contain's single quote"\\ -\label{sec-5.2}% -\item m='''"Contain's both"'''\\ -\label{sec-5.3}% -\end{itemize} % ends low level +\begin{verbatim} +l=[1,7,5,3,4] +3 in l +l[3]=21 +l +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 6} +\label{sec-17} + + Convert the string \~{}''Elizabeth is queen of england''\~{} to \~{}''Elizabeth is +queen''\~{} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 6} +\label{sec-18} + +\begin{verbatim} +s = "Elizabeth is queen of england" +stemp = s.split() +' '.join(stemp[:3]) +\end{verbatim} \end{frame} \begin{frame} \frametitle{Summary} -\label{sec-6} -\begin{itemize} +\label{sec-19} -\item a=73\\ -\label{sec-6.1}% -\item b=3.14\\ -\label{sec-6.2}% -\item c=3+4j\\ -\label{sec-6.3}% -\end{itemize} % ends low level -\end{frame} -\begin{frame} -\frametitle{Summary Contd.} -\label{sec-7} \begin{itemize} - -\item t=True\\ -\label{sec-7.1}% -\item f=False\\ -\label{sec-7.2}% -\item t and f\\ -\label{sec-7.3}% -\end{itemize} % ends low level +\item Number Datatypes -- integer,float and complex +\item Boolean and datatype and operators +\item Sequence data types -- List, String and Tuple +\item Accesing sequence +\item Slicing sequences +\item Finding length, sorting and reversing operations on sequences +\item Immutability +\end{itemize} \end{frame} \begin{frame} -\frametitle{Summary Contd.} -\label{sec-8} -\begin{itemize} - -\item l= [2,1,4,3]\\ -\label{sec-8.1}% -\item s='hello'\\ -\label{sec-8.2}% -\item tu=(1,2,3,4)\\ -\label{sec-8.3}% -\end{itemize} % ends low level -\end{frame} -\begin{frame} -\frametitle{Summary Contd.} -\label{sec-9} -\begin{itemize} +\frametitle{Thank you!} +\label{sec-20} -\item tu[-1]\\ -\label{sec-9.1}% -\item s[1:-1]\\ -\label{sec-9.2}% -\end{itemize} % ends low level -\end{frame} -\begin{frame} -\frametitle{Summary Contd.} -\label{sec-10} -\begin{itemize} - -\item Sorted(l)\\ -\label{sec-10.1}% -\item reversed(s)\\ -\label{sec-10.2}% -\end{itemize} % ends low level + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} \end{frame} \end{document} diff -r be96dc6c9743 -r 68813d8d80fb conditionals/questions.rst --- a/conditionals/questions.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/conditionals/questions.rst Thu Nov 11 02:28:55 2010 +0530 @@ -75,5 +75,27 @@ .. A minimum of 2 questions here (along with answers) -1. Question 1 -2. Question 2 +1. Given a number, say, n. If it is divisible by 10, print the + quotient when divided by 10, otherwise if it is divisible by 5, + print the corresponding quotient, otherwise, print the number. + + + Answer:: + + if n%10==0: + print n/10 + elif n%5==0: + print n/5 + else: + print n + +2. Given a number, say, n. Write an if block to multiply n by three + and add 1, if it is odd, otherwise halve it. + + Answer:: + + if n % 2: + n = n*3+1 + else: + n /= 2 + diff -r be96dc6c9743 -r 68813d8d80fb conditionals/quickref.tex --- a/conditionals/quickref.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/conditionals/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,8 +1,12 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} +Writing an if/elif/else block: +\begin{lstlisting} +if condition1: + # do A, B, C +elif condition2: + # do D, E +else: + # do Y, Z +\end{lstlisting} -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} - -Plotting two lists of equal length x, y:\\ -{\ex \lstinline| plot(x, y)|} +The ternary operator: +{\ex \lstinline| C if X else Y|} -- Do C if X is True else do Y. diff -r be96dc6c9743 -r 68813d8d80fb conditionals/script.rst --- a/conditionals/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/conditionals/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -1,14 +1,20 @@ .. Objectives .. ---------- -.. Clearly state the objectives of the LO (along with RBT level) +.. By the end of this tutorial, you will be able to + +.. * Use if/else blocks +.. * Use if/elif/else blocks +.. * Use the Ternary conditional statement - C if X else Y + +.. to check conditions in your programs. + .. Prerequisites .. ------------- -.. 1. Name of LO-1 -.. 2. Name of LO-2 -.. 3. Name of LO-3 +.. 1. Basic datatypes and operators + .. Author : Madhu Internal Reviewer : @@ -21,8 +27,7 @@ {{{ Show the slide containing the title }}} -Hello friends. Welcome to this spoken tutorial on Getting started with -strings. +Hello friends. Welcome to this spoken tutorial on Conditionals {{{ Show the slide containing the outline }}} @@ -40,10 +45,12 @@ Whenever we have two possible states that can occur depending on a whether a certain condition we can use if/else construct in -Python. Say for example we have a variable "a" which stores integers -and we are required to find out whether the value of the variable "a" -is an even number or an odd number. To test out conditional statements -as an example, let us say the value of the variable "a" is 5:: +Python. + +For example, say, we have a variable ``a`` which stores integers and +we are required to find out whether ``a`` is even or odd. an even +number or an odd number. Let's say the value of ``a`` is 5, now. +:: a = 5 @@ -54,36 +61,29 @@ else: print "Odd" -When the value of the variable "a" is divided by 2 and the remainder -is 0 i.e. the result of the operation "a modulo 2" is 0 the condition -"a % 2 == 0" evaluates to True, so the code within the if block gets -executed. This means that the value of "a" is Even. +If ``a`` is divisible by 2, i.e., the result of "a modulo 2" is 0, it +prints "Even", otherwise it prints "Odd". + +Note that in such a case, only one of the two blocks gets executed +depending on whether the condition is ``True`` or ``False``. -If the operation "a modulo 2" is not 0 the condition "a % 2 == 0" -evaluates to False and hence the code block within else gets executed -which means that the value of "a" is Odd. - -Note in such a case only one of the two blocks get executed depending -on whether the condition is True or False. +There is a very important sytactic element to understand here. Every +code block begins with a line that ends with a ``:``, in this example +the ``if`` and the ``else`` lines. Also, all the statements inside a +code block are intended by 4 spaces. Returning to the previous +indentation level, ends the code block. -There is a very important sytactic element to understand here. All the -statements which are inside a certain code block are indented by 4 -spaces. The statement which starts a new code block after it, i.e. the -if statement in this example ends with a colon (:). So the next -immediate line will be inside the if block and hence indented by 4 -spaces. To come out of the code block we have to come back to the -previous indentation level as shown in the else line here. Again the -line following else will be in a new block so else line ends with a -colon and the following block of code is indented by 4. +The if/else blocks work for a condition, which can take one of two +states. What do we do for conditions, which can take more than two +states? -As we use if/else statement when we have a condition which can take -one of the two states, we may have conditions which can take more than -two states. In such a scenario Python provides if/elif/else -statements. Let us take an example. We have a variable "a" which holds -integer values. We need to print "positive" if the value of a is -positive, "negative" if it is negative and "zero" if the value of the -variable "a" is 0. Let us use if/elif/else ladder for it. For the -purposes of testing our code let us assume that the value of a is -3:: +Python provides if/elif/else blocks, for such conditions. Let us take +an example. We have a variable ``a`` which holds integer values. We +need to print "positive" if ``a`` is positive, "negative" if +it is negative or "zero" if it is 0. + +Let us use if/elif/else ladder for it. For the purposes of testing our +code let us assume that the value of a is -3:: a = -3 @@ -94,18 +94,18 @@ else: print "zero" -This if/elif/else ladder is self explanatory. All the syntax and rules -as said for if/else statements hold. The only addition here is the -elif statement which can have another condition of its own. +All the syntax and rules as said for if/else statements hold. The only +addition here is the ``elif`` statement which can have another +condition of its own. -Here, exactly one block of code is executed and that block of code -corresponds to the condition which first evaluates to True. Even if -there is a situation where multiple conditions evaluate to True all -the subsequent conditions other than the first one which evaluates to -True are neglected. Consequently, the else block gets executed if and -only if all the conditions evaluate to False. +Here too, exactly one block of code is executed -- the block of code +which first evaluates to ``True``. Even if there is a situation where +multiple conditions evaluate to True all the subsequent conditions +other than the first one which evaluates to True are neglected. +Consequently, the else block gets executed if and only if all the +conditions evaluate to False. -Also, the else block in both if/else statement and if/elif/else is +Also, the ``else`` block in both if/else statement and if/elif/else is optional. We can have a single if statement or just if/elif statements without having else block at all. Also, there can be any number of elif's within an if/elif/else ladder. For example @@ -124,6 +124,21 @@ is completely valid. Note that there are multiple elif blocks and there is no else block. +Following is an exercise that you must do. + +%% %% Given a number, num. Write an if else block to print num, as is, + if it is divisible by 10, else print 10 * num. + +Please, pause the video here. Do the exercise and then continue. + +:: + + if num%10 == 0: + print num + else: + print 10*num + + In addition to these conditional statements, Python provides a very convenient ternary conditional operator. Let us take the following example where we read the marks data from a data file which is @@ -147,10 +162,21 @@ it is 0. This means that we make the scores of the students who were absent for the exam 0. -Moving on, there are certain situations where we will have to no -operations or statements within the block of code. For example, we -have a code where we are waiting for the keyboard input. If the user -enters "s" as the input we would perform some operation nothing +Following is an exercise that you must do. + +%% %% Given a number, num. Write a ternary operator to print num, as is, + if it is divisible by 10, else print 10 * num. + +Please, pause the video here. Do the exercise and then continue. + +:: + + print num if num%10 == 0 else 10*num + +Moving on, there are certain situations where we will have no +operations or statements within a block of code. For example, we have +a code where we are waiting for the keyboard input. If the user enters +"c", "d" or "x" as the input we would perform some operation nothing otherwise. In such cases "pass" statement comes very handy:: a = raw_input("Enter 'c' to calculate and exit, 'd' to display the existing @@ -167,8 +193,7 @@ In this case "pass" statement acts as a place holder for the block of code. It is equivalent to a null operation. It literally does -nothing. So "pass" statement can be used as a null operation -statement, or it can used as a place holder when the actual code +nothing. It can used as a place holder when the actual code implementation for a particular block of code is not known yet but has to be filled up later. diff -r be96dc6c9743 -r 68813d8d80fb conditionals/slides.org --- a/conditionals/slides.org Mon Nov 08 02:12:28 2010 +0530 +++ b/conditionals/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -18,7 +18,7 @@ #+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, #+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} -#+TITLE: Accessing parts of arrays +#+TITLE: Conditionals #+AUTHOR: FOSSEE #+EMAIL: #+DATE: @@ -30,81 +30,47 @@ #+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc * Outline - - Manipulating one and multi dimensional arrays - - Access and change individual elements - - Access and change rows and columns - - Slicing and striding on arrays to access chunks - - Read images into arrays and manipulations -* Sample Arrays - #+begin_src python - In []: A = array([12, 23, 34, 45, 56]) - - In []: C = array([[11, 12, 13, 14, 15], - [21, 22, 23, 24, 25], - [31, 32, 33, 34, 35], - [41, 42, 43, 44, 45], - [51, 52, 53, 54, 55]]) - - #+end_src + In this tutorial, we shall look at + + Using if/else blocks + + Using if/elif/else blocks + + Using the Ternary conditional statement + * Question 1 - Change the last column of ~C~ to zeroes. + Given a number, num. Write an if else block to print num, as is, if + it is divisible by 10, else print 10 * num. * Solution 1 #+begin_src python - In []: C[:, -1] = 0 + if num%10 == 0: + print num + else: + print 10*num + #+end_src + +* ~if/elif~ ladder + #+begin_src python + if user == 'admin': + # Do admin operations + elif user == 'moderator': + # Do moderator operations + elif user == 'client': + # Do customer operations #+end_src * Question 2 - Change ~A~ to ~[11, 12, 13, 14, 15]~. + Given a number, num. Write a ternary operator to print num, as is, + if it is divisible by 10, else print 10 * num. * Solution 2 #+begin_src python - In []: A[:] = [11, 12, 13, 14, 15] - #+end_src -* squares.png - #+begin_latex - \begin{center} - \includegraphics[scale=0.6]{squares} - \end{center} - #+end_latex -* Question 3 - - obtain ~[22, 23]~ from ~C~. - - obtain ~[11, 21, 31, 41]~ from ~C~. - - obtain ~[21, 31, 41, 0]~. -* Solution 3 - #+begin_src python - In []: C[1, 1:3] - In []: C[0:4, 0] - In []: C[1:5, 0] - #+end_src -* Question 4 - Obtain ~[[23, 24], [33, -34]]~ from ~C~ -* Solution 4 - #+begin_src python - In []: C[1:3, 2:4] - #+end_src -* Question 5 - Obtain the square in the center of the image -* Solution 5 - #+begin_src python - In []: imshow(I[75:225, 75:225]) - #+end_src -* Question 6 - Obtain the following - #+begin_src python - [[12, 0], [42, 0]] - [[12, 13, 14], [0, 0, 0]] - #+end_src - -* Solution 6 - #+begin_src python - In []: C[::3, 1::3] - In []: C[::4, 1:4] + print num if num%10 == 0 else 10*num #+end_src * Summary - You should now be able to -- - - Manipulate 1D \& Multi dimensional arrays - - Access and change individual elements - - Access and change rows and columns - - Slice and stride on arrays - - Read images into arrays and manipulate them. + In this tutorial session we learnt + + + What are conditional statements + + if/else statement + + if/elif/else statement + + Ternary conditional statement - ~C if X else Y~ + + and the ~pass~ statement + * Thank you! #+begin_latex \begin{block}{} diff -r be96dc6c9743 -r 68813d8d80fb conditionals/slides.tex --- a/conditionals/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/conditionals/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,95 +1,123 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\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} +% Created 2010-11-10 Wed 13:25 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{Conditionals} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + \begin{frame} - \maketitle +\frametitle{Outline} +\label{sec-1} + + In this tutorial, we shall look at +\begin{itemize} +\item Using if/else blocks +\item Using if/elif/else blocks +\item Using the Ternary conditional statement +\end{itemize} \end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + Given a number, num. Write an if else block to print num, as is, if + it is divisible by 10, else print 10 * num. +\end{frame} \begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +if num%10 == 0: + print num +else: + print 10*num +\end{lstlisting} \end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{if/elif} ladder} +\label{sec-4} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\lstset{language=Python} +\begin{lstlisting} +if user == 'admin': + # Do admin operations +elif user == 'moderator': + # Do moderator operations +elif user == 'client': + # Do customer operations +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-5} + Given a number, num. Write a ternary operator to print num, as is, + if it is divisible by 10, else print 10 * num. +\end{frame} \begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 2} +\label{sec-6} + +\lstset{language=Python} +\begin{lstlisting} +print num if num%10 == 0 else 10*num +\end{lstlisting} \end{frame} - \begin{frame} - \frametitle{Thank you!} +\frametitle{Summary} +\label{sec-7} + + In this tutorial session we learnt + +\begin{itemize} +\item What are conditional statements +\item if/else statement +\item if/elif/else statement +\item Ternary conditional statement - \texttt{C if X else Y} +\item and the \texttt{pass} statement +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-8} + \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r be96dc6c9743 -r 68813d8d80fb dictionaries/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dictionaries/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,20 @@ +Defining dictionary:\\ +{\ex \lstinline| d = {'k1':'v1', 'k2':'v2'}|} + +Access value using key in dictionary:\\ +{\ex \lstinline| print d['k1']|} + +Add key-value pair to dictionary:\\ +{\ex \lstinline| d['k3'] = 'v3'|} + +Delete key-value from dictionary:\\ +{\ex \lstinline| del d['k1']|} + +Check container-ship of key in dictionary:\\ +{\ex \lstinline| 'k2' in d|} + +List of keys in dictionary:\\ +{\ex \lstinline| d.keys()|} + +List of values in dictionary:\\ +{\ex \lstinline| d.values()|} diff -r be96dc6c9743 -r 68813d8d80fb getting-started-strings/quickref.tex --- a/getting-started-strings/quickref.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-strings/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,8 +1,8 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} +Creating a string:\\ +{\ex \lstinline| s = ``Hello World''|} -- Single quotes and triple +quotes can also be used. -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} +Accessing individual elements:\\ +{\ex \lstinline| s[5]|} -- Elements can be accessed with their index -Plotting two lists of equal length x, y:\\ -{\ex \lstinline| plot(x, y)|} +Strings are immutable. diff -r be96dc6c9743 -r 68813d8d80fb getting-started-strings/script.rst --- a/getting-started-strings/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-strings/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -30,9 +30,9 @@ {{{ Show the slide containing the outline }}} -In this tutorial, we will learn what do we actually mean by strings in -python, how python supports the use of strings. We will also learn -some of the operations that can be performed on strings. +In this tutorial, we will look at what we really mean by strings, how +python supports the use of strings and some of the operations that can +be performed on strings. {{{ Shift to terminal and start ipython }}} @@ -42,10 +42,9 @@ on the terminal -So what are strings? In Python anything within either single quotes +So, what are strings? In Python anything within either single quotes or double quotes or triple single quotes or triple double quotes are -strings. This is true whatsoever, even if there is only one character -within the quotes +strings. {{{ Type in ipython the following and read them as you type }}}:: @@ -54,19 +53,21 @@ '''This is a string as well''' """This is also a string""" 'p' + "" -Having more than one control character to define strings come as very -handy when one of the control characters itself is part of the -string. For example:: +Note that it really doesn't matter how many characters are present in +the string. The last example is a null string or an empty string. + +Having more than one control character to define strings is handy when +one of the control characters itself is part of the string. For +example:: "Python's string manipulation functions are very useful" -In this case we use single quote for apostrophe. If we had only single -quote to define strings we should have a clumsy way of escaping the -single quote character to make it part of the string. Hence this is a -very handy feature. +By having multiple control characters, we avoid the need for +escaping characters -- in this case the apostrophe. -The triple quoted strings let us define multi-lines strings without +The triple quoted strings let us define multi-line strings without using any escaping. Everything within the triple quotes is a single string no matter how many lines it extends:: @@ -99,19 +100,63 @@ gives another string in which the original string 'Hello' is repeated 5 times. -Since strings are collections we can access individual items in the -string using the subscripts:: +Following is an exercise that you must do. + +%% %% Obtain the string ``%% -------------------- %%`` (20 hyphens) + without typing out all the twenty hyphens. + +Please, pause the video here. Do the exercise and then continue. + +:: + + s = "%% " + "-"*20 + " %%" + +Let's now look at accessing individual elements of strings. Since, +strings are collections we can access individual items in the string +using the subscripts:: a[0] gives us the first character in the string. The indexing starts from 0 -for the first character up to n-1 for the last character. We can -access the strings from the end using negative indices:: +for the first character and goes up to n-1 for the last character. We +can access the strings from the end using negative indices:: + + a[-1] - a[-2] +gives us the last element of the string and +:: + + a[-2] gives us second element from the end of the string +Following is an exercise that you must do. + +%% %% Given a string, ``s = "Hello World"``, what is the output of:: + + s[-5] + s[-10] + s[-15] + +Please, pause the video here. Do the exercise and then continue. + +:: + + s[-5] + +gives us 'W' +:: + + s[-10] + +gives us 'e' and +:: + + s[-15] + +gives us an ``IndexError``, as should be expected, since the string +given to us is only 11 characters long. + Let us attempt to change one of the characters in a string:: a = 'hello' @@ -132,7 +177,7 @@ * How to define strings * Different ways of defining a string - * String concatenation and repeatition + * String concatenation and repetition * Accessing individual elements of the string * Immutability of strings diff -r be96dc6c9743 -r 68813d8d80fb getting-started-strings/slides.org --- a/getting-started-strings/slides.org Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-strings/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -18,7 +18,7 @@ #+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, #+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} -#+TITLE: Accessing parts of arrays +#+TITLE: #+AUTHOR: FOSSEE #+EMAIL: #+DATE: @@ -30,81 +30,38 @@ #+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc * Outline - - Manipulating one and multi dimensional arrays - - Access and change individual elements - - Access and change rows and columns - - Slicing and striding on arrays to access chunks - - Read images into arrays and manipulations -* Sample Arrays - #+begin_src python - In []: A = array([12, 23, 34, 45, 56]) - - In []: C = array([[11, 12, 13, 14, 15], - [21, 22, 23, 24, 25], - [31, 32, 33, 34, 35], - [41, 42, 43, 44, 45], - [51, 52, 53, 54, 55]]) - - #+end_src +*** Defining strings +*** Concatenation +*** Accessing individual elements +*** Immutability of strings * Question 1 - Change the last column of ~C~ to zeroes. + Obtain the string ~%% -------------------- %%~ (20 hyphens) without + typing out all the twenty hyphens. * Solution 1 #+begin_src python - In []: C[:, -1] = 0 + s = "%% " + "-"*20 + " %%" #+end_src * Question 2 - Change ~A~ to ~[11, 12, 13, 14, 15]~. + Given a string, ~s~ which is ~Hello World~ , what is the output of:: + #+begin_src python + s[-5] + s[-10] + s[-15] + #+end_src * Solution 2 #+begin_src python - In []: A[:] = [11, 12, 13, 14, 15] - #+end_src -* squares.png - #+begin_latex - \begin{center} - \includegraphics[scale=0.6]{squares} - \end{center} - #+end_latex -* Question 3 - - obtain ~[22, 23]~ from ~C~. - - obtain ~[11, 21, 31, 41]~ from ~C~. - - obtain ~[21, 31, 41, 0]~. -* Solution 3 - #+begin_src python - In []: C[1, 1:3] - In []: C[0:4, 0] - In []: C[1:5, 0] - #+end_src -* Question 4 - Obtain ~[[23, 24], [33, -34]]~ from ~C~ -* Solution 4 - #+begin_src python - In []: C[1:3, 2:4] - #+end_src -* Question 5 - Obtain the square in the center of the image -* Solution 5 - #+begin_src python - In []: imshow(I[75:225, 75:225]) - #+end_src -* Question 6 - Obtain the following - #+begin_src python - [[12, 0], [42, 0]] - [[12, 13, 14], [0, 0, 0]] - #+end_src - -* Solution 6 - #+begin_src python - In []: C[::3, 1::3] - In []: C[::4, 1:4] + 'W' + 'e' + IndexError #+end_src * Summary - You should now be able to -- - - Manipulate 1D \& Multi dimensional arrays - - Access and change individual elements - - Access and change rows and columns - - Slice and stride on arrays - - Read images into arrays and manipulate them. + In this tutorial we have learnt + + How to define strings + + Different ways of defining a string + + String concatenation and repetition + + Accessing individual elements of the string + + Immutability of strings + * Thank you! #+begin_latex \begin{block}{} diff -r be96dc6c9743 -r 68813d8d80fb getting-started-strings/slides.tex --- a/getting-started-strings/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-strings/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,95 +1,118 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\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} +% Created 2010-11-10 Wed 10:46 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} + + + + + + + + + + \begin{frame} - \maketitle +\frametitle{Outline} +\label{sec-1} +\begin{itemize} + +\item Defining strings\\ +\label{sec-1_1}% +\item Concatenation\\ +\label{sec-1_2}% +\item Accessing individual elements\\ +\label{sec-1_3}% +\item Immutability of strings\\ +\label{sec-1_4}% +\end{itemize} % ends low level \end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + Obtain the string \texttt{\%\% -------------------- \%\%} (20 hyphens) without + typing out all the twenty hyphens. +\end{frame} \begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +s = "%% " + "-"*20 + " %%" +\end{lstlisting} \end{frame} +\begin{frame}[fragile] +\frametitle{Question 2} +\label{sec-4} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - + Given a string, \texttt{s} which is \texttt{Hello World} , what is the output of:: +\lstset{language=Python} +\begin{lstlisting} +s[-5] +s[-10] +s[-15] +\end{lstlisting} +\end{frame} \begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 2} +\label{sec-5} + +\lstset{language=Python} +\begin{lstlisting} +'W' +'e' +IndexError +\end{lstlisting} \end{frame} - \begin{frame} - \frametitle{Thank you!} +\frametitle{Summary} +\label{sec-6} + + In this tutorial we have learnt +\begin{itemize} +\item How to define strings +\item Different ways of defining a string +\item String concatenation and repetition +\item Accessing individual elements of the string +\item Immutability of strings +\end{itemize} + + +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-7} + \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-arrays/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-arrays/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,14 @@ +Creating an array:\\ +{\ex \lstinline| a = array([[1,2,3,4],[5,6,7,8]])|} + +Finding shape of array:\\ +{\ex \lstinline| a.shape|} + +Reshape an array:\\ +{\ex \lstinline| a.reshape(4,2)|} + +Creating identity matrix:\\ +{\ex \lstinline| identity(3)|} + +Creating matrix with all zeros:\\ +{\ex \lstinline| z = zeros((4,2))|} diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-arrays/script.rst --- a/getting-started-with-arrays/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-with-arrays/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -34,14 +34,15 @@ {{{ switch to next slide, outline slide }}} -In this tutorial, we will learn about arrays, how to convert a list into an -array and also why an array is preferred over lists. And array operations. +In this tutorial, we will learn about arrays, we will learn how to convert +a list into an array array operations and also why an array is preferred +over lists. .. #[Puneeth: Fix the grammar above.] {{{ switch to next slide on overview of array }}} -Arrays are homogeneous data structures, unlike lists, arrays cannot have +Arrays are homogeneous data structures. Unlike lists, arrays cannot have heterogeneous data elements, that is, it can have only one type of data type, either all integers, or strings, or float, and not a mix. @@ -52,7 +53,7 @@ type of data, ....] Arrays are really fast in mathematical operations when compared to lists, -it is at least 80 to 100 times faster than lists. +because of the same type of data in arrays. .. #[Puneeth: For what size of an array is that the comparison? @@ -60,8 +61,12 @@ Now let us see how to create arrays. -I am assuming that you have your IPython interpreter running with the -``-pylab`` option, so that you have the required modules loaded. +Run your IPython interpreter with ``-pylab`` option, to load the required +modules to work with arrays. +{{{ take terminal and run the following command }}} +:: + + ipython -pylab .. #[Puneeth: 'I am assuming' doesn't sound right. Ask them to open if it .. is not open?] @@ -73,9 +78,12 @@ a1 = array([1,2,3,4]) Notice that here we created a one dimensional array. Also notice the object -we passed to create an array. Now let us see how to create a two -dimensional array. Pause here and try to do it yourself before looking at -the solution. +we passed to create an array. We passed a list to create an array. + +Now let us see how to create a two dimensional array. Pause here and try to +do it yourself before looking at the solution. + +{{{ switch to next slide, creating two dimensional arrays }}} .. #[Puneeth: I don't think this question can be solved by an average .. viewer. Questions during the tutorial, should generally be to re-iterate @@ -85,7 +93,8 @@ .. list, using the ``array`` function. Bring the later section about .. converting a list, here. A separate section is not necessary, IMHO.] -This is how we create two dimensional arrays. +We create two dimensional array by converting a list of lists to an array +as, :: @@ -94,7 +103,7 @@ .. #[Puneeth: Again, you could explain a bit about the fact that we are .. converting a list of lists.] -Let us see an easy method of creating an array with elements 1 to 8. +Now let us use ``arange()`` function to create the same array as before. :: @@ -103,7 +112,7 @@ .. #[Puneeth: say, creating the same array as before. for some time I got .. confused .] -And it created a single dimensional array of elements from 1 to 8. +And we obtained a single dimensional array with elements from 1 to 8. :: @@ -158,10 +167,9 @@ :: - a1.shape + a2.shape -``a1.shape`` object is a tuple, and since a1 is a single dimensional array, -it returned a tuple (4,). +``a2.shape`` object is a tuple, and it returned a tuple (2, 4). .. #[Puneeth: first show a 2D array, so that it becomes easier to explain. .. Also, the word ``tuple`` need not be mentioned. ] @@ -172,6 +180,13 @@ .. #[Puneeth: solution missing.] +It can be done as, +:: + + a1.shape + a3.shape + ar.shape + {{{ Array can have only a single type of data }}} .. #[Puneeth: I guess, this whole section can be skipped. If you want to @@ -214,9 +229,10 @@ .. #[Puneeth: something needs to motivate this. why are we suddenly talking .. of an identity matrix?] -An identity matrix is a square matrix in which all the diagonal elements -are one and rest of the elements zero. We can create an identity matrix -using the method ``identity()``. +Now let us see how to create identity matrix, an identity matrix is a +square matrix in which all the diagonal elements are one and rest of the +elements zero. We can create an identity matrix using the method +``identity()``. The function ``identity()`` takes an integer argument, @@ -224,7 +240,7 @@ identity(3) -As you can see the identity method returned a three by three square array +As you can see the identity method returned a three by three square matrix with all the diagonal elements as one and the rest of the elements as zero. .. #[Puneeth: You say array here, matrix there -- it's a bit messed up. @@ -306,8 +322,8 @@ {{{ switch to next slide, summary slide }}} So this brings us to the end of this tutorial, in this tutorial we covered -basics of arrays, how to create an array, converting a list to an array, -basic array operations etc. +basics of arrays, learned how to create an array, saw how to convert a list +to an array, and basic array operations etc. .. #[Puneeth: s/how to create an array/creating an array] diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-arrays/slides.org --- a/getting-started-with-arrays/slides.org Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-with-arrays/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -44,9 +44,12 @@ * Creating Arrays - Creating a 1-dimensional array : In []: a1 = array([1, 2, 3, 4]) + ~[1, 2, 3, 4]~ is a list. +* Creating two-dimensional array - Creating a 2-dimensional array : In []: a2 = array([[1,2,3,4],[5,6,7,8]]) - - Easier method of creating array with consecutive elements. + here we convert a list of lists to an array making a 2-d array. + - Using ~arange()~ function : In []: ar = arange(1,9) * ~reshape()~ method - To reshape an array @@ -67,11 +70,11 @@ * ~.shape~ of array - ~.shape~ To find the shape of the array - : In []: a1.shape + : In []: a2.shape - ~.shape~ returns a tuple of shape * Exercise 2 - Find out the shape of the other arrays(a2, a3, ar) that we have created. + Find out the shape of the other arrays(a1, a3, ar) that we have created. * Homogeneous data - All elements in array should be of same type : In []: a4 = array([1,2,3,'a string']) diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-arrays/slides.tex --- a/getting-started-with-arrays/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-with-arrays/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,4 +1,4 @@ -% Created 2010-10-12 Tue 00:20 +% Created 2010-11-07 Sun 15:18 \documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} \usepackage[T1]{fontenc} @@ -87,6 +87,12 @@ In []: a1 = array([1, 2, 3, 4]) \end{verbatim} + \texttt{[1, 2, 3, 4]} is a list. +\end{frame} +\begin{frame}[fragile] +\frametitle{Creating two-dimensional array} +\label{sec-4} + \begin{itemize} \item Creating a 2-dimensional array \end{itemize} @@ -95,6 +101,7 @@ In []: a2 = array([[1,2,3,4],[5,6,7,8]]) \end{verbatim} + here we convert a list of lists to an array making a 2-d array. \begin{itemize} \item Easier method of creating array with consecutive elements. \end{itemize} @@ -105,7 +112,7 @@ \end{frame} \begin{frame}[fragile] \frametitle{\texttt{reshape()} method} -\label{sec-4} +\label{sec-5} \begin{itemize} \item To reshape an array @@ -119,7 +126,7 @@ \end{frame} \begin{frame}[fragile] \frametitle{Creating \texttt{array} from \texttt{list}.} -\label{sec-5} +\label{sec-6} \begin{itemize} \item \texttt{array()} method accepts list as argument @@ -137,13 +144,13 @@ \end{frame} \begin{frame} \frametitle{Exercise 1} -\label{sec-6} +\label{sec-7} Create a 3-dimensional array of the order (2, 2, 4). \end{frame} \begin{frame}[fragile] \frametitle{\texttt{.shape} of array} -\label{sec-7} +\label{sec-8} \begin{itemize} \item \texttt{.shape} @@ -158,13 +165,13 @@ \end{frame} \begin{frame} \frametitle{Exercise 2} -\label{sec-8} +\label{sec-9} Find out the shape of the other arrays(a2, a3, ar) that we have created. \end{frame} \begin{frame}[fragile] \frametitle{Homogeneous data} -\label{sec-9} +\label{sec-10} \begin{itemize} \item All elements in array should be of same type @@ -176,7 +183,7 @@ \end{frame} \begin{frame}[fragile] \frametitle{Implicit type casting} -\label{sec-10} +\label{sec-11} \begin{verbatim} In []: a4 @@ -186,7 +193,7 @@ \end{frame} \begin{frame} \frametitle{\texttt{identity()}, \texttt{zeros()} methods} -\label{sec-11} +\label{sec-12} \begin{itemize} \item \texttt{identity(n)} @@ -197,7 +204,7 @@ \end{frame} \begin{frame} \frametitle{Learning exercise} -\label{sec-12} +\label{sec-13} \begin{itemize} \item Find out about @@ -212,7 +219,7 @@ \end{frame} \begin{frame} \frametitle{Array operations} -\label{sec-13} +\label{sec-14} \begin{itemize} \item \texttt{a1 * 2} @@ -247,7 +254,7 @@ \end{frame} \begin{frame} \frametitle{Summary} -\label{sec-14} +\label{sec-15} In this tutorial we covered, \begin{itemize} @@ -259,7 +266,7 @@ \end{frame} \begin{frame} \frametitle{Thank you!} -\label{sec-15} +\label{sec-16} \begin{block}{} \begin{center} diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-for/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-for/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,6 @@ +For loop:\\ +{\ex \lstinline| for i in range(1,11,2):|} +{\ex \lstinline| s = s + i|} + +Range function:\\ +{\ex \lstinline| range([start,]stop[,step])|} diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-for/script.rst --- a/getting-started-with-for/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-with-for/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -168,6 +168,8 @@ 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, 7056, 576, 2916 +Pause here and try to solve the problem before proceeding further. + {{{ switch to next slide, problem statement of second problem in solved exercise}}} diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-functions/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-functions/questions.rst Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,112 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. What will the function do? + :: + + def what(x) + return x*x + + 1. Returns the square of x + #. Returns x + #. Function doesn't have docstring + #. Error + + Answer: Error + +2. What will the function do? + :: + + def what(x): + return x*x + + 1. Returns the square of x + #. Returns x + #. Function doesn't have docstring + #. Error + + Answer: Returns the square of x + +3. How many arguments can be passed to a python function? + + 1. None + #. One + #. Two + #. Any + + Answer: Any + +4. How many values can a python function return? + + 1. None + #. One + #. Two + #. Any + + Answer: Any + +5. A python function can return only one value + + 1. True + #. False + + Answer: False + +6. What will be the output of the following code? + :: + + def avg(a, b): + return (a + b) / 2 + + print avg(10,11) + + 1. 10 + #. 10.5 + #. 11 + #. 9.5 + + Answer: 10 + +7. What will be the output of the following code? + :: + + def avg(a, b): + return (a + b) / 2 + + print avg(10,11.0) + + 1. 10 + #. 10.5 + #. 11 + #. 9.5 + + Answer: 10.5 + +8. What will be the output of the following code? + :: + + def what(a, b): + return a + b / 2 + + print avg(10,11) + + 1. 10 + #. 10.5 + #. 16 + #. 15 + + Answer: 15 + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Write a python function to check the numbers a, b c is a Pythagorean + triplet or not. + +2. Write a python function which will accept an n digit number and + which returns the reverse of the number. diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-functions/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-functions/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,4 @@ +Defining a function:\\ +{\ex \lstinline| def name([arguments]):|} +{\ex \lstinline| code|} +{\ex \lstinline| [return values]|} diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-functions/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-functions/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,291 @@ +.. Objectives +.. ---------- + +.. 8.1 LO: getting started with functions (3) + +.. At the end of this tutorial, you will be able to + +.. 1. define function +.. #. define functions with arguments +.. #. learn about docstrings +.. #. learn about return values +.. can return multiple values +.. #. read code + + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` installed. +.. #. getting started with ``ipython``. + + +.. Author : Anoop Jacob Thomas + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + + +============================== +Getting started with functions +============================== + +{{{ show welcome slide }}} + +Hello and welcome to the tutorial getting started with functions. + +{{{ switch to next slide, outline slide }}} + +In this tutorial we will learn about functions in python, how to +define functions, arguments to functions, docstrings, and function +return value. + +{{{ switch to next slide, Function }}} + +While writing code, we always want to reduce the number of lines of +code and functions is a way of reusing the code. Thus the same lines +of code can be used again and again. A function is a portion of code +within a larger program that performs a specific task and is +relatively independent of the remaining code. Now let us get more +familiar with functions, + +{{{ switch to next slide, f(x) a mathematical function }}} + +Consider a mathematical function f(x) = x square. Here x is a variable +and with different values of x the value of function will change. When +x is one f(1) will return the value 1 and f(2) will return us the +value 4. Let us now see how to define the function f(x) in python. + +{{{ switch to next slide, define f(x) in Python }}} + +In your Ipython interpreter type the following, +:: + + def f(x): + return x*x + +Well that defined the function, so before learning what we did let us +see if it returns the expected values, try, +:: + + f(1) + f(2) + +Yes, it returned 1 and 2 respectively. And now let us see what we did, +we wrote two lines. The first line ``def f(x)`` is used to define the +name and the parameters to the function. ``def`` is a keyword and +``f`` is the name of the function and ``x`` the parameter of the +function. + +{{{ switch to next slide, problem statement 1 }}} + +%% 1 %% Write a python function named cube which computes the cube of + a given number n. + +Pause here and try to solve the problem yourself. + +{{{ switch to next slide, solution }}} + +The problem can be solved as, +:: + + def cube(n): + return n**3 + +And now let us see how to write functions without arguments. + +{{{ switch to next slide, greet function }}} + +let us define a new function called ``greet`` which will print ``Hello +World``. +:: + + def greet(): + print "Hello World!" + +now try calling the function, +:: + + greet() + +Well that is a function which takes no arguments. Also note that it is +not mandatory for a function to return values. The function ``greet`` +neither takes any argument nor returns any value. + +Now let us see how to write functions with more than one argument. + +{{{ switch to next slide, exercise 2 }}} + +%% 2 %% Write a python function named ``avg`` which computes the + average of ``a`` and ``b``. + +Pause here and try to solve the problem yourself. + +{{{ switch to next slide, solution 2 }}} + +The problem can be solved as, +:: + + def avg(a,b): + return (a + b)/2 + +Thus if we want a function to accept more arguments, we just list them +separated with a comma between the parenthesis after the function name +in the ``def`` line. + +{{{ switch to next slide, docstring }}} + +It is always a good practice to document the code that we write, and +for a function we define we should write an abstract of what the +function does, and that is called a docstring. Let us modify the +function ``avg`` and add docstring to it. Do the following, +:: + + def avg(a,b): + """ avg takes two numbers as input (a & b), and + returns the average of a and b""" + return (a+b)/2 + +Note that docstrings are entered in the immediate line after the +function definition and put as a triple quoted string. And here as far +as the code functionality is concerned, we didn't do anything. We just +added an abstract of what the function does. + +Now try this in the ipython interpreter. +:: + + avg? + +It displays the docstring as we gave it. Thus docstring is a good way +of documenting the function we write. + +Try to do this, +:: + + f? + +It doesn't have a docstring associated with it. Also we cannot infer +anything from the function name, and thus we are forced to read the +code to understand anything about the function. + +{{{ switch to next slide, exercise 3 }}} + +%% 3 %% Add docstring to the function f. + +Pause here and try to do it yourself. + +{{{ switch to next slide, solution }}} + +We need to define the function again to add docstring to the function +``f`` and we do it as, +:: + + def f(x): + """Accepts a number x as argument and, + returns the square of the number x.""" + return x*x + +{{{ switch to next slide, exercise 4 }}} + +%% 4 %% Write a python function named ``circle`` which returns the + area and perimeter of a circle given radius ``r``. + +Pause here and try to solve the problem yourself. + +{{{ switch to next slide, solution 4 }}} + +The problem requires us to return two values instead of one which we +were doing till now. We can solve the problem as, +:: + + def circle(r): + """returns area and perimeter of a circle given radius r""" + pi = 3.14 + area = pi * r * r + perimeter = 2 * pi * r + return area, perimeter + +A python function can return any number of values. There is no +restriction for it. + +Let us call the function ``circle`` as, +:: + + a, p = circle(6) + print a + print p + +Now we have done enough coding, let us do some code reading exercise, + +{{{ switch to next slide, what }}} + +What does the function ``what`` do? + +.. def what( n ): +.. if n < 0: n = -n +.. while n > 0: +.. if n % 2 == 1: +.. return False +.. n /= 10 +.. return True + +Pause here and try to figure out what the function ``what`` does. + +{{{ switch to next slide, even_digits }}} + +.. def even_digits( n ): +.. """returns True if all the digits of number n is even +.. returns False if all the digits of number n is not even""" +.. if n < 0: n = -n +.. while n > 0: +.. if n % 2 == 1: +.. return False +.. n /= 10 +.. return True + +The function returns ``True`` if all the digits of the number ``n`` +are even, otherwise it returns ``False``. + +Now one more code reading exercise, + +{{{ switch to next slide, what }}} + +What does the function ``what`` do? + +.. def what( n ): +.. i = 1 +.. while i * i < n: +.. i += 1 +.. return i * i == n, i + +Pause here and try to figure out what the function ``what`` does. + +{{{ switch to next slide, is_perfect_square }}} + +.. def is_perfect_square( n ): +.. """returns True and square root of n, if n is a perfect square, +.. otherwise returns False and the square root of the +.. next perfect square""" +.. i = 1 +.. while i * i < n: +.. i += 1 +.. return i * i == n, i + + +The function returns ``True`` and the square root of ``n`` if n is a +perfect square, otherwise it returns ``False`` and the square root of +the next perfect square. + +This brings us to the end of this tutorial, in this tutorial we covered + +{{{ switch to next slide, summary }}} + +- Functions in Python +- Passing parameters to a function +- Returning values from a function + +We also did few code reading exercises. + +{{{ switch to next slide, Thank you }}} + +Thank you! diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-functions/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-functions/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,211 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Getting started with functions +#+AUTHOR: FOSSEE +#+EMAIL: info@fossee.in +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Define functions + - Pass arguments to functions + - Learn about docstrings + - Return values from functions + +* Function + - Eliminate code redundancy + - Help in code reuse + - Subroutine + - relatively independent of remaining code + +* ~f(x)~ a mathematical function + + $f(x) = x^{2}$ + + : f(1) -> 1 + : f(2) -> 4 + +* Define ~f(x)~ in Python + #+begin_src python + def f(x): + return x*x + #+end_src + + - ~def~ - keyword + - ~f~ - function name + - ~x~ - parameter / argument to function ~f~ + +* Exercise 1 + + Write a python function named ~cube~ which computes the cube of a given + number ~n~. + + - Pause here and try to solve the problem yourself. + +* Solution + #+begin_src python + def cube(n): + return n**3 + #+end_src + +* ~greet~ function + + Function ~greet~ which will print ~Hello World!~. + #+begin_src python + def greet(): + print "Hello World!" + #+end_src + - Call the function ~greet~ + : In []: greet() + : Hello World! + +* Exercise 2 + + Write a python function named ~avg~ which computes the average of + ~a~ and ~b~. + + - Pause here and try to solve the problem yourself. + +* Solution 2 + #+begin_src python + def avg(a,b): + return (a + b)/2 + #+end_src + + - ~a~ and ~b~ are parameters + - ~def f(p1, p2, p3, ... , pn)~ + +* Docstring + + - Documenting/commenting code is a good practice + #+begin_src python + def avg(a,b): + """ avg takes two numbers as input + (a & b), and returns the average + of a and b""" + return (a+b)/2 + #+end_src + - Docstring + - written in the line after the ~def~ line. + - Inside triple quote. + - Documentation + : avg? +* Exercise 3 + Add docstring to the function f. + +* Solution 3 + +#+begin_src python + def f(x): + """Accepts a number x as argument and, + returns the square of the number x.""" + return x*x +#+end_src + +* Exercise 4 + Write a python function named ~circle~ which returns the area and + perimeter of a circle given radius ~r~. + +* Solution 4 +#+begin_src python + def circle(r): + """returns area and perimeter of a circle given + radius r""" + pi = 3.14 + area = pi * r * r + perimeter = 2 * pi * r + return area, perimeter +#+end_src + +* ~what~ +#+begin_src python + + def what( n ): + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True +#+end_src + +* ~even_digits~ +#+begin_src python + def even_digits( n ): + """returns True if all the digits of number + n is even returns False if all the digits + of number n is not even""" + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True +#+end_src + +* ~what~ +#+begin_src python + def what( n ): + i = 1 + while i * i < n: + i += 1 + return i * i == n, i +#+end_src + +* ~is_perfect_square~ +#+begin_src python + def is_perfect_square( n ): + """returns True and square root of n, + if n is a perfect square, otherwise + returns False and the square root + of the next perfect square""" + i = 1 + while i * i < n: + i += 1 + return i * i == n, i +#+end_src + +* Summary + - Functions in Python + - Passing parameters to a function + - Returning values from a function + + - We also did few code reading exercises. + +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-functions/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-functions/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,318 @@ +% Created 2010-11-10 Wed 18:59 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Getting started with functions} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Define functions +\item Pass arguments to functions +\item Learn about docstrings +\item Return values from functions +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Function} +\label{sec-2} + +\begin{itemize} +\item Eliminate code redundancy +\item Help in code reuse +\item Subroutine + +\begin{itemize} +\item relatively independent of remaining code +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{f(x)} a mathematical function} +\label{sec-3} + + + $f(x) = x^{2}$ + +\begin{verbatim} + f(1) -> 1 + f(2) -> 4 +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Define \texttt{f(x)} in Python} +\label{sec-4} + +\begin{verbatim} +def f(x): + return x*x +\end{verbatim} + +\begin{itemize} +\item \texttt{def} - keyword +\item \texttt{f} - function name +\item \texttt{x} - parameter / argument to function \texttt{f} +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 1} +\label{sec-5} + + + Write a python function named \texttt{cube} which computes the cube of a given + number \texttt{n}. + +\begin{itemize} +\item Pause here and try to solve the problem yourself. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution} +\label{sec-6} + +\begin{verbatim} +def cube(n): + return n**3 +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{greet} function} +\label{sec-7} + + + Function \texttt{greet} which will print \texttt{Hello World!}. +\begin{verbatim} +def greet(): + print "Hello World!" +\end{verbatim} +\begin{itemize} +\item Call the function \texttt{greet} +\begin{verbatim} + In []: greet() + Hello World! +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 2} +\label{sec-8} + + + Write a python function named \texttt{avg} which computes the average of + \texttt{a} and \texttt{b}. + +\begin{itemize} +\item Pause here and try to solve the problem yourself. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-9} + +\begin{verbatim} +def avg(a,b): + return (a + b)/2 +\end{verbatim} + +\begin{itemize} +\item \texttt{a} and \texttt{b} are parameters +\item \texttt{def f(p1, p2, p3, ... , pn)} +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Docstring} +\label{sec-10} + + +\begin{itemize} +\item Documenting/commenting code is a good practice +\begin{verbatim} +def avg(a,b): + """ avg takes two numbers as input + (a & b), and returns the average + of a and b""" + return (a+b)/2 +\end{verbatim} +\item Docstring + +\begin{itemize} +\item written in the line after the \texttt{def} line. +\item Inside triple quote. +\end{itemize} + +\item Documentation +\begin{verbatim} + avg? +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 3} +\label{sec-11} + + Add docstring to the function f. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 3} +\label{sec-12} + + +\begin{verbatim} +def f(x): + """Accepts a number x as argument and, + returns the square of the number x.""" + return x*x +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Exercise 4} +\label{sec-13} + + Write a python function named \texttt{circle} which returns the area and + perimeter of a circle given radius \texttt{r}. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 4} +\label{sec-14} + +\begin{verbatim} +def circle(r): + """returns area and perimeter of a circle given + radius r""" + pi = 3.14 + area = pi * r * r + perimeter = 2 * pi * r + return area, perimeter +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{what}} +\label{sec-15} + +\begin{verbatim} + +def what( n ): + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{even\_digits}} +\label{sec-16} + +\begin{verbatim} +def even_digits( n ): + """returns True if all the digits of number + n is even returns False if all the digits + of number n is not even""" + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{what}} +\label{sec-17} + +\begin{verbatim} +def what( n ): + i = 1 + while i * i < n: + i += 1 + return i * i == n, i +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{is\_perfect\_square}} +\label{sec-18} + +\begin{verbatim} +def is_perfect_square( n ): + """returns True and square root of n, + if n is a perfect square, otherwise + returns False and the square root + of the next perfect square""" + i = 1 + while i * i < n: + i += 1 + return i * i == n, i +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-19} + +\begin{itemize} +\item Functions in Python +\item Passing parameters to a function +\item Returning values from a function +\item We also did few code reading exercises. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-20} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-lists/questions.rst.orig --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-lists/questions.rst.orig Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,56 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. How do you create an empty list? :: + + empty=[] + +2. What is the most important property of sequence data types like lists? + + The elements are in order and can be accessed by index numbers. + +3. Can you have a list inside a list ? + + Yes,List can contain all the other data types, including list. + + Example: + list_in_list=[2.3,[2,4,6],'string,'all datatypes can be there'] + +4. What is the index number of the first element in a list? + + 0 + nonempty = ['spam', 'eggs', 100, 1.234] + nonempty[0] + +5. How would you access the end of a list without finding its length? + + Using negative indices. We can the list from the end using negative indices. + + :: + nonempty = ['spam', 'eggs', 100, 1.234] + nonempty[-1] + +6. What is the function to find the length of a list? + + len + +7. Delete the last element from list sq=[5,4,3,2,1,0] + + del(sq[-1]) + +8. How many will you have to use remove function to remove all 6's from the given list sq=[2,5,6,7,6,4,6]? + + 3 + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Add all elemets of seq1=['e','f','g','h'] +to the sequence seq=['a','b','c','d'] + +2. Delete all elements of seq1=[3,5,6] from sequence + seq=[1,2,3,4,5,6,7,8,9] diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-lists/script.rst --- a/getting-started-with-lists/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-with-lists/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -19,18 +19,20 @@ .. #. getting started with lists .. #. basic datatypes -.. Author : Puneeth - Internal Reviewer : Amit +.. Author : Amit + Internal Reviewer : Anoop Jacob Thomas External Reviewer : Checklist OK? : [2010-10-05] +.. #[[Anoop: Slides contain only outline and summary + Script ------ + {{{ Show the slide containing title }}} + Hello friends and welcome to the tutorial on getting started with lists. - {{{ Show the slide containing title }}} - {{{ Show the slide containing the outline slide }}} In this tutorial we will be getting acquainted with a python data @@ -40,11 +42,15 @@ * Structure of lists * Access list elements * Append elements to lists - * Deleting elements from lists + * Delete elements from lists List is a compound data type, it can contain data of other data types. List is also a sequence data type, all the elements are in -order and there order has a meaning. +order and the order has a meaning. + +.. #[[Anoop: "all the elements are in order and **there** order has a + meaning." - I guess something is wrong here, I am not able to + follow this.]] We will first create an empty list with no elements. On your IPython shell type :: @@ -55,43 +61,58 @@ This is an empty list without any elements. -* Filled lists +.. #[[Anoop: the document has to be continous, without any + subheadings, removing * Filled lists]] -Lets now define a list, nonempty and fill it with some random elements. +Lets now see how to define a non-empty list. We do it as,:: -nonempty = ['spam', 'eggs', 100, 1.234] + nonempty = ['spam', 'eggs', 100, 1.234] Thus the simplest way of creating a list is typing out a sequence of comma-separated values (items) between square brackets. -All the list items need not have the same data type. - - +All the list items need not be of the same data type. As we can see lists can contain different kinds of data. In the -previous example 'spam' and 'eggs' are strings and 100 and 1.234 +previous example 'spam' and 'eggs' are strings and 100 and 1.234 are integer and float. Thus we can put elements of heterogenous types in -lists. Thus list themselves can be one of the element types possible -in lists. Thus lists can also contain other lists. Example :: +lists including list itself. + +.. #[[Anoop: the sentence "Thus list themselves can be one of the + element types possible in lists" is not clear, rephrase it.]] - list_in_list=[[4,2,3,4],'and', 1, 2, 3, 4] +Example :: + + listinlist=[[4,2,3,4],'and', 1, 2, 3, 4] -We access list elements using the number of index. The -index begins from 0. So for list nonempty, nonempty[0] gives the -first element, nonempty[1] the second element and so on and -nonempty[3] the last element. :: +We access list elements using the index. The index begins from 0. So +for list nonempty, nonempty[0] gives the first element, nonempty[1] +the second element and so on and nonempty[3] the last element. :: nonempty[0] nonempty[1] nonempty[3] -We can also access the elememts from the end using negative indices :: +Following is an exercise that you must do. + +%% %% What happens when you do nonempty[-1]. + +Please, pause the video here. Do the exercise and then continue. + +.. #[[Anoop: was negative indices introduced earlier, if not may be we + can ask them to try out nonempty[-1] and see what happens and then + tell that it gives the last element in the list.]] + +As you can see you get the last element which is 1.234. + + +In python negative indices are used to access elements from the end:: nonempty[-1] nonempty[-2] nonempty[-4] --1 gives the last element which is the 4th element , -2 second to last and -4 gives the fourth -from last element which is first element. +-1 gives the last element which is the 4th element , -2 second to last +and -4 gives the fourth from last element which is first element. We can append elements to the end of a list using append command. :: @@ -100,12 +121,23 @@ nonempty.append(6) nonempty -As we can see non empty appends 'onemore' and 6 at the end. +Following are exercises that you must do. + +%% %% What is the syntax to get the element 'and' +in the list,listinlist ? +%% %% How would you get 'and' using negative indices? + +Please, pause the video here. Do the exercise and then continue. + +The solution is on your screen + + +As we can see non empty appends 'onemore' and 6 at the end. Using len function we can check the number of elements in the list -nonempty. In this case it being 6 :: +nonempty. In this case it 6 :: len(nonempty) @@ -121,23 +153,50 @@ deletes the element at index 1, i.e the second element of the list, 'eggs'. The other way is removing element by content. Lets say one wishes to delete 100 from nonempty list the syntax of the command -should be :: - - nonempty.remove(100) +should be -but what if their were two 100's. To check that lets do a small +.. #[[Anoop: let x = [1,2,1,3] + now x.remove(x[2]) + still x is [2,1,3] so that is not the way to remove + element by index, it removed first occurrence of 1(by + content) and not based on index, so make necessary + changes]] + +:: + + nonempty.remove(100) + +but what if there were two 100's. To check that lets do a small experiment. :: - nonempty.append('python') + nonempty.append('spam') nonempty - nonempty.remove('python') + nonempty.remove('spam') nonempty -If we check a now we will see that the first occurence 'spam' is removed +If we check now we will see that the first occurence 'spam' is removed thus remove removes the first occurence of the element in the sequence and leaves others untouched. + + + +.. #[[Anoop: does it have two spams or two pythons?]] + +.. #[[Anoop: there are no exercises/solved problems in this script, + add them]] + +Following are exercises that you must do. + +%% %% Remove the third element from the list, listinlist. + +%% %% Remove 'and' from the list, listinlist. + +Please, pause the video here. Do the exercise and then continue. + + + {{{Slide for Summary }}} @@ -151,7 +210,7 @@ -{{{ Sponsored by Fossee Slide }}} +{{{ show Sponsored by Fossee Slide }}} This tutorial was created as a part of FOSSEE project. @@ -159,7 +218,7 @@ Thank You - +.. * Author : Amit Sethi * First Reviewer : * Second Reviewer : Nishanth diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-lists/script.rst.orig --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-lists/script.rst.orig Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,224 @@ +.. Objectives +.. ---------- + +.. By the end of this tutorial, you will be able to + +.. Create Lists. +.. Access List elements. +.. Append elemets to list +.. Delete list elemets + +.. 1. getting started with ipython + + + +.. Prerequisites +.. ------------- + +.. 1. getting started with strings +.. #. getting started with lists +.. #. basic datatypes + +.. Author : Amit + Internal Reviewer : Anoop Jacob Thomas + External Reviewer : + Checklist OK? : [2010-10-05] + +.. #[[Anoop: Slides contain only outline and summary + +Script +------ + {{{ Show the slide containing title }}} + +Hello friends and welcome to the tutorial on getting started with +lists. + + {{{ Show the slide containing the outline slide }}} + +In this tutorial we will be getting acquainted with a python data +structure called lists. We will learn :: + + * How to create lists + * Structure of lists + * Access list elements + * Append elements to lists + * Delete elements from lists + +List is a compound data type, it can contain data of other data +types. List is also a sequence data type, all the elements are in +order and the order has a meaning. + +.. #[[Anoop: "all the elements are in order and **there** order has a + meaning." - I guess something is wrong here, I am not able to + follow this.]] + +We will first create an empty list with no elements. On your IPython +shell type :: + + empty = [] + type(empty) + + +This is an empty list without any elements. + +.. #[[Anoop: the document has to be continous, without any + subheadings, removing * Filled lists]] + +Lets now see how to define a non-empty list. We do it as,:: + + nonempty = ['spam', 'eggs', 100, 1.234] + +Thus the simplest way of creating a list is typing out a sequence +of comma-separated values (items) between square brackets. +All the list items need not be of the same data type. + +As we can see lists can contain different kinds of data. In the +previous example 'spam' and 'eggs' are strings and 100 and 1.234 are +integer and float. Thus we can put elements of heterogenous types in +lists including list itself. + +.. #[[Anoop: the sentence "Thus list themselves can be one of the + element types possible in lists" is not clear, rephrase it.]] + +Example :: + + listinlist=[[4,2,3,4],'and', 1, 2, 3, 4] + +We access list elements using the index. The index begins from 0. So +for list nonempty, nonempty[0] gives the first element, nonempty[1] +the second element and so on and nonempty[3] the last element. :: + + nonempty[0] + nonempty[1] + nonempty[3] + +Following is an exercise that you must do. + +%% %% What happens when you do nonempty[-1]. + +Please, pause the video here. Do the exercise and then continue. + +.. #[[Anoop: was negative indices introduced earlier, if not may be we + can ask them to try out nonempty[-1] and see what happens and then + tell that it gives the last element in the list.]] + +As you can see you get the last element which is 1.234. + + +In python negative indices are used to access elements from the end:: + + nonempty[-1] + nonempty[-2] + nonempty[-4] + +-1 gives the last element which is the 4th element , -2 second to last +and -4 gives the fourth from last element which is first element. + +We can append elements to the end of a list using append command. :: + + nonempty.append('onemore') + nonempty + nonempty.append(6) + nonempty + +Following are exercises that you must do. + +%% %% What is the syntax to get the element 'and' +in the list,listinlist ? + + +%% %% How would you get 'and' using negative indices? + +Please, pause the video here. Do the exercise and then continue. + +The solution is on your screen + + +As we can see non empty appends 'onemore' and 6 at the end. + +Using len function we can check the number of elements in the list +nonempty. In this case it 6 :: + + len(nonempty) + + + +Just like we can append elements to a list we can also remove them. +There are two ways of doing it. One is by using index. :: + + del(nonempty[1]) + + + +deletes the element at index 1, 'eggs' which is the second element of +the list. The other way is removing element by content. Lets say one +wishes to delete 100 from nonempty list the syntax of the command +should be + +.. #[[Anoop: let x = [1,2,1,3] + now x.remove(x[2]) + still x is [2,1,3] so that is not the way to remove + element by index, it removed first occurrence of 1(by + content) and not based on index, so make necessary + changes]] + +:: + + nonempty.remove(100) + +but what if there were two 100's. To check that lets do a small +experiment. :: + + nonempty.append('spam') + nonempty + nonempty.remove('spam') + nonempty + +If we check now we will see that the first occurence 'spam' is removed +thus remove removes the first occurence of the element in the sequence +and leaves others untouched. + + + + + +.. #[[Anoop: does it have two spams or two pythons?]] + +.. #[[Anoop: there are no exercises/solved problems in this script, + add them]] + +Following are exercises that you must do. + +%% %% Remove the third element from the list, listinlist. + +%% %% Remove 'and' from the list, listinlist. + +Please, pause the video here. Do the exercise and then continue. + + + +{{{Slide for Summary }}} + + +In this tutorial we came across a sequence data type called lists. :: + + * We learned how to create lists. + * How to access lists. + * Append elements to list. + * Delete Element from list. + * And Checking list length. + + + +{{{ show Sponsored by Fossee Slide }}} + +This tutorial was created as a part of FOSSEE project. + +I hope you found this tutorial useful. + +Thank You + +.. + * Author : Amit Sethi + * First Reviewer : + * Second Reviewer : Nishanth diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-lists/slides.org --- a/getting-started-with-lists/slides.org Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-with-lists/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -2,34 +2,99 @@ #+LaTeX_CLASS_OPTIONS: [presentation] #+BEAMER_FRAME_LEVEL: 1 -#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} #+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) #+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC -#+OPTIONS: H:5 num:t toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} -#+TITLE: Plotting Data +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Getting started with Lists #+AUTHOR: FOSSEE #+DATE: 2010-09-14 Tue #+EMAIL: info@fossee.in -# \author[FOSSEE] {FOSSEE} +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc -# \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -# \date{} -* Tutorial Plan -** How to create lists -** Structure of lists -** Access list elements -** Append elements to lists -** Deleting elements from lists +* Outline + - How to create lists + - Structure of lists + - Access list elements + - Append elements to lists + - Deleting elements from lists + + +* Question 1 + - What happens when you do nonempty[-1]. + +* Solution 1 + - It gives the last element , 1.234 + +* Questions + - What is the syntax to get the element 'and' +in the list,listinlist ? + - How would you get 'and' using negative indices? + +* Solutions +#+begin_src python + + listinlist[1] + listinlist[-5] + +#+end_src python +* Questions + + - Remove the third element from the list, listinlist. + + - Remove 'and' from the list, listinlist. + +* Solutions +#+begin_src python + + del(listinlist[2]) + listinlist.remove('and') + +#+end_src python * Summary - +#+begin_src python + l=[1,2,3,4] l[-1] l.append(5) del(l[2]) + l.remove(2) len(l) +#+end_src python +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-lists/slides.tex --- a/getting-started-with-lists/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-with-lists/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,95 +1,138 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\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} +% Created 2010-11-10 Wed 12:22 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} \usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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}} +\title{Getting started with Lists} +\author{FOSSEE} +\date{2010-09-14 Tue} -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date{} - -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} -\begin{frame} - \maketitle -\end{frame} +\maketitle -\begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} -\end{frame} + + -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + -\begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} -\end{frame} + + \begin{frame} - \frametitle{Thank you!} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item How to create lists +\item Structure of lists +\item Access list elements +\item Append elements to lists +\item Deleting elements from lists +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + +\begin{itemize} +\item What happens when you do nonempty[-1]. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Solution 1} +\label{sec-3} + +\begin{itemize} +\item It gives the last element , 1.234 +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Questions} +\label{sec-4} + +\begin{itemize} +\item What is the syntax to get the element `and' +\end{itemize} + +in the list,listinlist ? + + +\begin{itemize} +\item How would you get `and' using negative indices? +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solutions} +\label{sec-5} + +\begin{verbatim} + +listinlist[1] +listinlist[-5] +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Questions} +\label{sec-6} + + +\begin{itemize} +\item Remove the third element from the list, listinlist. +\item Remove `and' from the list, listinlist. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solutions} +\label{sec-7} + +\begin{verbatim} + +del(listinlist[2]) +listinlist.remove('and') +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Summary} +\label{sec-8} + +\begin{verbatim} + +l=[1,2,3,4] +l[-1] +l.append(5) +del(l[2]) +l.remove(2) +len(l) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-9} + \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-symbolics/script.rst --- a/getting-started-with-symbolics/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-with-symbolics/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -4,7 +4,7 @@ .. By the end of this tutorial, you will be able to .. 1. Defining symbolic expressions in sage. -.. # Using built-in costants and functions. +.. # Using built-in constants and functions. .. # Performing Integration, differentiation using sage. .. # Defining matrices. .. # Defining Symbolic functions. @@ -37,7 +37,7 @@ {{{ Show outline slide }}} * Defining symbolic expressions in sage. -* Using built-in costants and functions. +* Using built-in constants and functions. * Performing Integration, differentiation using sage. * Defining matrices. * Defining Symbolic functions. @@ -73,26 +73,32 @@ var('x,alpha,y,beta') x^2/alpha^2+y^2/beta^2 -taking another example +taking another example :: var('theta') - sin^2(theta)+cos^2(theta) - + sin(theta)*sin(theta)+cos(theta)*cos(theta) -Similarly, we can define many algebraic and trigonometric expressions -using sage . +Similarly, we can define many algebraic and trigonometric expressions using sage . -Sage also provides a few built-in constants which are commonly used in -mathematics . +Following is an exercise that you must do. -example : pi,e,infinity , Function n gives the numerical values of all these - constants. +%% %% Define following expressions as symbolic expressions +in sage? + + 1. x^2+y^2 + #. y^2-4ax + +Please, pause the video here. Do the exercise and then continue. -{{{ Type n(pi) - n(e) - n(oo) - On the sage notebook }}} +The solution is on your screen. + + +Sage also provides a few built-in constants which are commonly used in mathematics . + +example : pi,e,infinity , Function n gives the numerical values of all these constants. + +{{{ Type n(pi) n(e) n(oo) On the sage notebook }}} @@ -131,6 +137,24 @@ log(e,e) +Following is are exercises that you must do. + +%% %% Find the values of the following constants upto 6 digits precision + + 1. pi^2 + #. euler_gamma^2 + + +%% %% Find the value of the following. + + 1. sin(pi/4) + #. ln(23) + +Please, pause the video here. Do the exercises and then continue. + +The solutions are on your screen. + + Given that we have defined variables like x,y etc .. , We can define an arbitrary function with desired name in the following way.:: @@ -157,13 +181,16 @@ var('x') - h(x)=x^2 g(x)=1 + h(x)=x^2 + g(x)=1 f=Piecewise( {{{ Show the documentation of Piecewise }}} :: - f=Piecewise([[(0,1),h(x)],[(1,2),g(x)]],x) f + f=Piecewise([[(0,1),h(x)],[(1,2),g(x)]],x) + f + @@ -184,9 +211,7 @@ var('n') function('f', n) - f(n) = 1/n^2 - sum(f(n), n, 1, oo) @@ -200,6 +225,18 @@ This series converges to pi/4. +Following are exercises that you must do. + +%% %% Define the piecewise function. + f(x)=3x+2 + when x is in the closed interval 0 to 4. + f(x)=4x^2 + between 4 to 6. + +%% %% Sum of 1/(n^2-1) where n ranges from 1 to infinity. + +Please, pause the video here. Do the exercise(s) and then continue. + Moving on let us see how to perform simple calculus operations using Sage For example lets try an expression first :: @@ -267,6 +304,22 @@ as we can see when we substitute the value the answer is almost = 0 showing the solution we got was correct. +Following is an (are) exercise(s) that you must do. + +%% %% Differentiate the following. + + 1. sin(x^3)+log(3x) , degree=2 + #. x^5*log(x^7) , degree=4 + +%% %% Integrate the given expression + + sin(x^2)+exp(x^3) + +%% %% Find x + cos(x^2)-log(x)=0 + Does the equation have a root between 1,2. + +Please, pause the video here. Do the exercises and then continue. @@ -286,8 +339,18 @@ A.inverse() +Following is an (are) exercise(s) that you must do. -{{{ Part of the notebook with summary }}} +%% %% Find the determinant and inverse of : + + A=[[x,0,1][y,1,0][z,0,y]] + +Please, pause the video here. Do the exercise(s) and then continue. + + + + +{{{ Show the summary slide }}} So in this tutorial we learnt how to diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-symbolics/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-symbolics/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,166 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Getting started with symbolics +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Defining symbolic expressions in sage. + - Using built-in constants and functions. + - Performing Integration, differentiation using sage. + - Defining matrices. + - Defining Symbolic functions. + - Simplifying and solving symbolic expressions and functions. + +* Questions 1 + - Define the following expression as symbolic + expression in sage. + + - x^2+y^2 + - y^2-4ax + +* Solutions 1 +#+begin_src python + var('x,y') + x^2+y^2 + + var('a,x,y') + y^2-4*a*x +#+end_src python +* Questions 2 + - Find the values of the following constants upto 6 digits precision + + - pi^2 + + + - Find the value of the following. + + - sin(pi/4) + - ln(23) + +* Solutions 2 +#+begin_src python + n(pi^2,digits=6) + n(sin(pi/4)) + n(log(23,e)) +#+end_src python +* Question 2 + - Define the piecewise function. + f(x)=3x+2 + when x is in the closed interval 0 to 4. + f(x)=4x^2 + between 4 to 6. + + - Sum of 1/(n^2-1) where n ranges from 1 to infinity. + +* Solution Q1 +#+begin_src python + var('x') + h(x)=3*x+2 + g(x)= 4*x^2 + f=Piecewise([[(0,4),h(x)],[(4,6),g(x)]],x) + f +#+end_src python +* Solution Q2 +#+begin_src python + var('n') + f=1/(n^2-1) + sum(f(n), n, 1, oo) +#+end_src python + + +* Questions 3 + - Differentiate the following. + + - x^5*log(x^7) , degree=4 + + - Integrate the given expression + + - x*sin(x^2) + + - Find x + - cos(x^2)-log(x)=0 + - Does the equation have a root between 1,2. + +* Solutions 3 +#+begin_src python + var('x') + f(x)= x^5*log(x^7) + diff(f(x),x,5) + + var('x') + integral(x*sin(x^2),x) + + var('x') + f=cos(x^2)-log(x) + find_root(f(x)==0,1,2) +#+end_src + +* Question 4 + - Find the determinant and inverse of : + + A=[[x,0,1][y,1,0][z,0,y]] + +* Solution 4 +#+begin_src python + var('x,y,z') + A=matrix([[x,0,1],[y,1,0],[z,0,y]]) + A.det() + A.inverse() +#+end_src +* Summary + - We learnt about defining symbolic + expression and functions. + - Using built-in constants and functions. + - Using to see the documentation of a + function. + +* Summary + - Simple calculus operations . + - Substituting values in expression + using substitute function. + - Creating symbolic matrices and + performing operation on them . + +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + + diff -r be96dc6c9743 -r 68813d8d80fb getting-started-with-symbolics/slides.tex --- a/getting-started-with-symbolics/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/getting-started-with-symbolics/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,21 +1,34 @@ -% Created 2010-10-21 Thu 00:06 +% Created 2010-11-10 Wed 17:18 \documentclass[presentation]{beamer} -\usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} \usepackage[latin1]{inputenc} \usepackage[T1]{fontenc} +\usepackage{fixltx2e} \usepackage{graphicx} \usepackage{longtable} \usepackage{float} \usepackage{wrapfig} \usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} \usepackage{amssymb} \usepackage{hyperref} - +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\title{Plotting Data } +\title{Getting started with symbolics} \author{FOSSEE} -\date{2010-09-14 Tue} +\date{} +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} \maketitle @@ -25,43 +38,222 @@ + + + \begin{frame} -\frametitle{Tutorial Plan} +\frametitle{Outline} \label{sec-1} + \begin{itemize} +\item Defining symbolic expressions in sage. +\item Using built-in constants and functions. +\item Performing Integration, differentiation using sage. +\item Defining matrices. +\item Defining Symbolic functions. +\item Simplifying and solving symbolic expressions and functions. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Questions 1} +\label{sec-2} + +\begin{itemize} +\item Define the following expression as symbolic + expression in sage. + +\begin{itemize} +\item x$^2$+y$^2$ +\item y$^2$-4ax +\end{itemize} + +\end{itemize} + + +\end{frame} +\begin{frame}[fragile] +\frametitle{Solutions 1} +\label{sec-3} + +\begin{verbatim} +var('x,y') +x^2+y^2 + +var('a,x,y') +y^2-4*a*x +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Questions 2} +\label{sec-4} + +\begin{itemize} +\item Find the values of the following constants upto 6 digits precision + +\begin{itemize} +\item pi$^2$ +\end{itemize} + +\item Find the value of the following. + +\begin{itemize} +\item sin(pi/4) +\item ln(23) +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solutions 2} +\label{sec-5} + +\begin{verbatim} +n(pi^2,digits=6) +n(sin(pi/4)) +n(log(23,e)) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-6} -\item Defining symbolic expressions in sage.\\ -\label{sec-1.1}% -\item Using built-in costants and functions.\\ -\label{sec-1.2}% -\item Performing Integration, differentiation using sage.\\ -\label{sec-1.3}% -\item Defining matrices.\\ -\label{sec-1.4}% -\item Defining Symbolic functions.\\ -\label{sec-1.5}% -\item Simplifying and solving symbolic expressions and functions.\\ -\label{sec-1.6}% -\end{itemize} % ends low level +\begin{itemize} +\item Define the piecewise function. + f(x)=3x+2 + when x is in the closed interval 0 to 4. + f(x)=4x$^2$ + between 4 to 6. +\item Sum of 1/(n$^2$-1) where n ranges from 1 to infinity. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution Q1} +\label{sec-7} + +\begin{verbatim} +var('x') +h(x)=3*x+2 +g(x)= 4*x^2 +f=Piecewise([[(0,4),h(x)],[(4,6),g(x)]],x) +f +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution Q2} +\label{sec-8} + +\begin{verbatim} +var('n') +f=1/(n^2-1) +sum(f(n), n, 1, oo) +\end{verbatim} + +\end{frame} +\begin{frame} +\frametitle{Questions 3} +\label{sec-9} + +\begin{itemize} +\item Differentiate the following. + +\begin{itemize} +\item x$^5$*log(x$^7$) , degree=4 +\end{itemize} + +\item Integrate the given expression + +\begin{itemize} +\item x*sin(x$^2$) +\end{itemize} + +\item Find x + +\begin{itemize} +\item cos(x$^2$)-log(x)=0 +\item Does the equation have a root between 1,2. +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solutions 3} +\label{sec-10} + +\begin{verbatim} +var('x') +f(x)= x^5*log(x^7) +diff(f(x),x,5) + +var('x') +integral(x*sin(x^2),x) + +var('x') +f=cos(x^2)-log(x) +find_root(f(x)==0,1,2) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-11} + +\begin{itemize} +\item Find the determinant and inverse of : + + A=[[x,0,1][y,1,0][z,0,y]] +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 4} +\label{sec-12} + +\begin{verbatim} +var('x,y,z') +A=matrix([[x,0,1],[y,1,0],[z,0,y]]) +A.det() +A.inverse() +\end{verbatim} \end{frame} \begin{frame} \frametitle{Summary} -\label{sec-2} +\label{sec-13} + \begin{itemize} +\item We learnt about defining symbolic + expression and functions. +\item Using built-in constants and functions. +\item Using to see the documentation of a + function. +\end{itemize} + + +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-14} -\item We learnt about defining symbolic expression and functions.\\ -\label{sec-2.1}% -\item Using built-in constants and functions.\\ -\label{sec-2.2}% -\item Using to see the documentation of a function.\\ -\label{sec-2.3}% -\item Simple calculus operations .\\ -\label{sec-2.4}% -\item Substituting values in expression using substitute function.\\ -\label{sec-2.5}% -\item Creating symbolic matrices and performing operation on them .\\ -\label{sec-2.6}% -\end{itemize} % ends low level +\begin{itemize} +\item Simple calculus operations . +\item Substituting values in expression + using substitute function. +\item Creating symbolic matrices and + performing operation on them . +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-15} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} \end{frame} \end{document} diff -r be96dc6c9743 -r 68813d8d80fb input_output/script.rst --- a/input_output/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/input_output/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -12,24 +12,24 @@ .. 1. Loops .. Author : Nishanth Amuluru - Internal Reviewer : + Internal Reviewer : Puneeth External Reviewer : Checklist OK? : [2010-10-05] Script ------ -Hello friends and welcome to the tutorial on Input/Output +Hello friends and welcome to this tutorial on Input/Output {{{ Show the slide containing title }}} {{{ Show the slide containing the outline slide }}} Input and Output are used in almost every program we use. -In this tutorial, we shall learn +In this tutorial, we shall learn how to - * Outputting data - * Taking input from the user + * Output data + * Take input from the user type :: @@ -38,10 +38,14 @@ a print a -print a prints the value of a which is obvious. + +``print a``, obviously, is printing the value of ``a``. + As you can see, even when you type just a, the value of a is shown. But there is a difference. +.. #[Amit: The next sentence does seem to be clear enough] + Typing a shows the value of a while print a prints the string. This difference becomes more evident when we use strings with newlines in them. type @@ -57,10 +61,17 @@ Moreover when we type just a, the value a is shown only in interactive mode and does not have any effect on the program while running it as a script. +.. #[punch: I think we could show that?] + We shall look at different ways of outputting the data. -print statement also accepts the syntax of C's printf statement. + +.. #[Amit: C's printf syntax ?? i think its better to elaborate the + idea] + +print statement in python supports string formatting. Various arguments can be passed to print using modifiers. + type :: @@ -69,7 +80,8 @@ z = "zed" print "x is %2.1f y is %d z is %s"%(x,y) -As you can see, the values of x and y are substituted in place of %2.1f and %d +As you can see, the values of x and y are substituted in place of +``%2.1f`` and ``%d`` {{{ Pause here and try out the following exercises }}} @@ -77,12 +89,12 @@ {{{ continue from paused state }}} -We see that the int value of x and float value of y are printed corresponding -to the modifiers used in the print statement. +We see that the ``int`` value of x and ``float`` value of y are +printed corresponding to the modifiers used in the print statement. -We can also see that print statement prints a new line character at the end of -line, everytime it is called. This can be suppressed by using a "," at the end -print statement. +We can also see that ``print`` statement prints a new line character +at the end of the line, everytime it is called. This can be suppressed +by using a "," at the end ``print`` statement. Let us see this by typing out following code on an editor as print_example.py @@ -168,24 +180,27 @@ {{{ Pause here and try out the following exercises }}} -%% 4 %% How do you display a prompt and let the user enter input in a new line +%% 4 %% How do you display a prompt and let the user enter input in next line {{{ continue from paused state }}} .. #[Puneeth: We didn't talk of new-line character till now, did we?] .. #[Puneeth: non-programmers might not know?] +.. #[Amit: Well there is a discussion earlier about new lines, I think its good +.. as a slight trick question. But may be next line is a more easier lexicon] + The trick is to include a newline character at the end of the prompt string. :: ip = raw_input("Please enter a number in the next line\n> ") -prints the newline character and hence the user enters input in the new line +prints the newline character and hence the user enters input in the next line {{{ Show summary slide }}} This brings us to the end of the tutorial. -we have learnt +In this totorial we have learnt * How to print some value * How to print using modifiers @@ -194,9 +209,9 @@ {{{ Show the "sponsored by FOSSEE" slide }}} -#[Nishanth]: Will add this line after all of us fix on one. + This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India Hope you have enjoyed and found it useful. -Thankyou +Thank You. diff -r be96dc6c9743 -r 68813d8d80fb input_output/script.rst.orig --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/input_output/script.rst.orig Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,222 @@ +.. Objectives +.. ---------- + +.. #. How to print some value +.. #. How to print using modifiers +.. #. How to take input from user +.. #. How to display a prompt to the user before taking the input + +.. Prerequisites +.. ------------- + +.. 1. Loops + +.. Author : Nishanth Amuluru + Internal Reviewer : Puneeth + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +Hello friends and welcome to this tutorial on Input/Output + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +Input and Output are used in almost every program we use. +In this tutorial, we shall learn how to + + * Output data + * Take input from the user + +type +:: + + a = "This is a string" + a + print a + +<<<<<<< local +print a, prints the value of a. +======= +``print a``, obviously, is printing the value of ``a``. +>>>>>>> other +As you can see, even when you type just a, the value of a is shown. +But there is a difference. + +.. #[Amit: The next sentence does seem to be clear enough] + +Typing a shows the value of a while print a prints the string. This difference +becomes more evident when we use strings with newlines in them. +type +:: + + b = "A line \n New line" + b + print b + +As you can see, just typing b shows that b contains a newline character. +While typing print b prints the string and hence the newline. + +Moreover when we type just a, the value a is shown only in interactive mode and +does not have any effect on the program while running it as a script. + +.. #[punch: I think we could show that?] + +We shall look at different ways of outputting the data. + +<<<<<<< local +.. #[Amit: C's printf syntax ?? i think its better to elaborate the + idea] + +print statement in python supports string formatting. +Various arguments can be passed to print using modifiers. +======= +``print`` statement also accepts the syntax of C's ``printf`` statement. +Various arguments can be passed to ``print`` using modifiers. +>>>>>>> other +type +:: + + x = 1.5 + y = 2 + z = "zed" + print "x is %2.1f y is %d z is %s"%(x,y) + +As you can see, the values of x and y are substituted in place of +``%2.1f`` and ``%d`` + +{{{ Pause here and try out the following exercises }}} + +%% 1 %% What happens when you do ``print "x is %d y is %f" %(x, y)`` + +{{{ continue from paused state }}} + +We see that the ``int`` value of x and ``float`` value of y are +printed corresponding to the modifiers used in the print statement. + +We can also see that ``print`` statement prints a new line character +at the end of the line, everytime it is called. This can be suppressed +by using a "," at the end ``print`` statement. + +Let us see this by typing out following code on an editor as print_example.py + +{{{ open an editor }}} +type +:: + + print "Hello" + print "World" + + print "Hello", + print "World" + +Now we run the script using %run /home/fossee/print_example.py + +As we can see, the print statement when used with comma in the end, prints a +space instead of a new line. + +Now we shall look at taking input from the user. +We will use the ~~raw_input~~ for this. +type +:: + + ip = raw_input() + +The cursor is blinking indicating that it is waiting for input +type +:: + + an input + +and hit enter. +Now let us see what is the value of ip by typing. +:: + + ip + +We can see that it contains the string "an input" + +{{{ Pause here and try out the following exercises }}} + +%% 2 %% enter the number 5.6 as input and store it in a variable called c. + +{{{ continue from paused state }}} + +We have to use the raw_input command with variable c. +type +:: + + c = raw_input() + 5.6 + c + +Now let us see the type of c. + +:: + + type(c) + +We see that c is a string. This implies that anything you enter as input, will +be taken as a string no matter what you enter. + +{{{ Pause here and try out the following exercises }}} + +%% 3 %% What happens when you do not enter anything and hit enter + +{{{ continue from paused state }}} + +:: + + d = raw_input() + + d + +We see that when nothing is entered, an empty string is considered as input. + +raw_input also can display a prompt to assist the user. +:: + + name = raw_input("Please enter your name: ") + +prints the string given as argument and then waits for the user input. + +{{{ Pause here and try out the following exercises }}} + +%% 4 %% How do you display a prompt and let the user enter input in next line + +{{{ continue from paused state }}} + +.. #[Puneeth: We didn't talk of new-line character till now, did we?] +.. #[Puneeth: non-programmers might not know?] + +.. #[Amit: Well there is a discussion earlier about new lines, I think its good +.. as a slight trick question. But may be next line is a more easier lexicon] + +The trick is to include a newline character at the end of the prompt string. +:: + + ip = raw_input("Please enter a number in the next line\n> ") + +prints the newline character and hence the user enters input in the next line + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +In this totorial we have learnt + + * How to print some value + * How to print using modifiers + * How to take input from user + * How to display a prompt to the user before taking the input + +{{{ Show the "sponsored by FOSSEE" slide }}} + + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank You. + diff -r be96dc6c9743 -r 68813d8d80fb loops/script.rst --- a/loops/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/loops/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -32,15 +32,14 @@ {{{ Show the outline slide }}} In this tutorial, we shall look at ``while`` and ``for`` loops. We -shall then look at the ``break``, ``continue`` and ``pass`` keywords -and how to use them. +shall then look at how to break out of them, or skip some iterations +in loops. .. #[[Anoop: for loop is a pre-requisite and has been already covered, so i think our emphasize can be on while loops]] -.. #[[Anoop: Instead of saying we will learn keywords pass, break and - continue, I think it is better to tell them that we will learn more - about loops]] +.. #[[punch: I think, we should have both of them. It gives a better +.. context and comparison.] {{{ switch to the ipython terminal }}} @@ -145,8 +144,8 @@ .. #[[Anoop: should add slides for break, continue, pass]] Say, we wish to print the squares of all the odd numbers below 10, -which are not multiples of 3, we would modify the for loop as follows. -:: +which are not multiples of 3, we would modify the ``for`` loop as +follows. :: for n in range(1, 10, 2): if n%3 == 0: @@ -158,12 +157,9 @@ {{{ switch to next slide }}} -%%3%%Using the ``continue`` keyword modify the ``for`` loop to print -the squares of even numbers below 10, to print the squares of only -multiples of 4. (Do not modify the range function call.) - -.. #[[Anoop: can you be more explicit/specific on do no modify say we - can ask them to use range(2, 10, 2) and solve the problem]] +%%3%%Using the ``continue`` keyword modify the ``for`` loop, with the +``range(2, 10, 2)``, to print the squares of even numbers below 10, to +print the squares of only multiples of 4. Please, pause the video here. Do the exercise and then continue. diff -r be96dc6c9743 -r 68813d8d80fb manipulating-lists/quickref.tex --- a/manipulating-lists/quickref.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/manipulating-lists/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,8 +1,10 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} +Slicing \& Striding a list:\\ +{\ex \lstinline| A[start:stop:step]|} \lstinline|stop| excluded -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} +Sorting a list:\\ +{\ex \lstinline| sorted(A)|} -- returns new list +{\ex \lstinline| A.sort()|} -- in-place sort -Plotting two lists of equal length x, y:\\ -{\ex \lstinline| plot(x, y)|} +Reversing a list:\\ +{\ex \lstinline| A[::-1]|} -- returns new list +{\ex \lstinline| A.reverse()|} -- in-place reverse diff -r be96dc6c9743 -r 68813d8d80fb manipulating-lists/script.rst --- a/manipulating-lists/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/manipulating-lists/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -22,13 +22,12 @@ Hello friends. Welcome to this spoken tutorial on Manipulating Lists. - {{{ Show the slide containing the outline }}} We have already learnt a lot about Lists in Python. In this tutorial, we will learn more about advanced features of Lists in Python. We will -see in detail how to concatenate two lists, slicing and striding of -lists, methods to sort and reverse the list. +see how to concatenate two lists, details of slicing and striding of +lists, methods to sort and reverse lists. {{{ Shift to terminal and start ipython }}} @@ -40,8 +39,8 @@ We already know what Lists are in Python, how to access individual elements in the list and some of the functions that can be run on the -lists like max, min, sum len and so on. Now let us learn some of the -basic operations that can be performed on Lists. +lists like ``max, min, sum, len`` and so on. Now let us learn some of +the basic operations that can be performed on Lists. We already know how to access individual elements in a List. But what if we have a scenario where we need to get a part of the entire list @@ -64,6 +63,18 @@ was the element with the index 4 was included but 23 which was the element with index 8 was excluded. +Following is an exercise you must do. + +%% %% Obtain the primes less than 10, from the list ``primes``. + +Please, pause the video here, do the exercise and then resume. + +:: + + primes[0:4] + +will give us the primes below 10. + Generalizing, we can obtain a slice of the list "p" from the index "start" upto the index "end" but excluding "end" with the following syntax @@ -79,12 +90,12 @@ num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] If we want to obtain all the odd numbers less than 10 from the list -"num" we have to start from element with index 1 upto the index 10 in +``num`` we have to start from element with index 1 upto the index 10 in steps of 2:: num[1:10:2] -So if we don't specify the step it is by default 1. Similary there are +When no step is specified, it is assumed to be 1. Similarly, there are default values for start and stop indices as well. If we don't specify the start index it is implicitly taken as the first element of the list:: @@ -105,6 +116,19 @@ gives us all the even numbers in the list "num". +Following is an exercise that you must do. + +%% %% Obtain all the multiples of three from the list ``num``. + +Please, pause the video here. Do the exercise and then continue. + +:: + + num[::3] + +gives us all the multiples of 3 from the list, since every third +element in it, starting from 0, is divisible by 3. + The other basic operation that we can perform on list is concatenation of two or more lists. We can combine two lists by using the "plus" operator. Say we have @@ -122,17 +146,16 @@ c It is important to observe that the "plus" operator always returns a -new list without touching anything in the existing lists which are the -operands of the concatenation operation. +new list without altering the lists being concatenated in any way. -We know that list is a collection of data. Whenever we have a -collection we run into situations where we want to start the +We know that a list is a collection of data. Whenever we have a +collection we run into situations where we want to sort the collection. Lists support sort method which sorts the list inplace:: a = [5, 1, 6, 7, 7, 10] a.sort() -Now the contents of the list "a" will be:: +Now the contents of the list ``a`` will be:: a [1, 5, 6, 7, 7, 10] @@ -164,27 +187,46 @@ a [5, 4, 3, 2, 1] -But again the original list is lost. If we want to obtain the reverse -of a list keeping the original list intact we can use the Python -built-in function reversed. reversed function returns a new list which -is the reverse of the list which was passed as the argument to the -reversed function:: +But again the original list is lost. +.. #[punch: removed reversed, since it returns an iterator] - a = [1, 2, 3, 4, 5] - reversed(a) +To reverse a list, we could use striding with negative indexing.:: + + a[::-1] We can also store this new reversed list in another list variable. +Following is an (are) exercise(s) that you must do. + +%% %% Given a list of marks of students in an examination, obtain a + list with marks in descending order. + :: + + marks = [99, 67, 47, 100, 50, 75, 62] + +Please, pause the video here. Do the exercise(s) and then continue. + +:: + + sorted(marks)[::-1] + +OR + +:: + + sorted(marks, reverse = True) + + + {{{ Show summary slide }}} This brings us to the end of another session. In this tutorial session we learnt - * How to define strings - * Different types of defining a string - * String concatenation and repeatition - * Accessing individual elements of the string - * Immutability of strings + * Obtaining parts of lists using slicing and striding + * List concatenation + * Sorting lists + * Reversing lists {{{ Show the "sponsored by FOSSEE" slide }}} diff -r be96dc6c9743 -r 68813d8d80fb manipulating-lists/slides.org --- a/manipulating-lists/slides.org Mon Nov 08 02:12:28 2010 +0530 +++ b/manipulating-lists/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -18,7 +18,7 @@ #+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, #+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} -#+TITLE: Accessing parts of arrays +#+TITLE: Manipulating Lists #+AUTHOR: FOSSEE #+EMAIL: #+DATE: @@ -28,83 +28,54 @@ #+LANGUAGE: en #+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t #+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc +#+STARTUP: align fold nodlcheck hidestars oddeven lognotestate * Outline - - Manipulating one and multi dimensional arrays - - Access and change individual elements - - Access and change rows and columns - - Slicing and striding on arrays to access chunks - - Read images into arrays and manipulations -* Sample Arrays - #+begin_src python - In []: A = array([12, 23, 34, 45, 56]) - - In []: C = array([[11, 12, 13, 14, 15], - [21, 22, 23, 24, 25], - [31, 32, 33, 34, 35], - [41, 42, 43, 44, 45], - [51, 52, 53, 54, 55]]) - - #+end_src + In this session we shall be looking at + - Concatenating lists + - Obtaining parts of lists + - Sorting lists + - Reversing lists * Question 1 - Change the last column of ~C~ to zeroes. + Obtain the primes less than 10, from the list ~primes~. * Solution 1 #+begin_src python - In []: C[:, -1] = 0 - #+end_src + primes[0:4] + #+end_src python +* Slicing + #+begin_src python + p[start:stop] + #+end_src python + - Returns all elements of ~p~ between ~start~ and ~stop~ + - The element with index equal to ~stop~ is *not* included. * Question 2 - Change ~A~ to ~[11, 12, 13, 14, 15]~. + Obtain all the multiples of three from the list ~num~. * Solution 2 #+begin_src python - In []: A[:] = [11, 12, 13, 14, 15] - #+end_src -* squares.png - #+begin_latex - \begin{center} - \includegraphics[scale=0.6]{squares} - \end{center} - #+end_latex + num[::3] + #+end_src python * Question 3 - - obtain ~[22, 23]~ from ~C~. - - obtain ~[11, 21, 31, 41]~ from ~C~. - - obtain ~[21, 31, 41, 0]~. + Given a list of marks of students in an examination, obtain a list + with marks in descending order. + #+begin_src python + marks = [99, 67, 47, 100, 50, 75, 62] + #+end_src python * Solution 3 #+begin_src python - In []: C[1, 1:3] - In []: C[0:4, 0] - In []: C[1:5, 0] - #+end_src -* Question 4 - Obtain ~[[23, 24], [33, -34]]~ from ~C~ -* Solution 4 - #+begin_src python - In []: C[1:3, 2:4] - #+end_src -* Question 5 - Obtain the square in the center of the image -* Solution 5 + sorted(marks)[::-1] + #+end_src python +OR #+begin_src python - In []: imshow(I[75:225, 75:225]) - #+end_src -* Question 6 - Obtain the following - #+begin_src python - [[12, 0], [42, 0]] - [[12, 13, 14], [0, 0, 0]] - #+end_src + sorted(marks, reverse=True) + #+end_src python -* Solution 6 - #+begin_src python - In []: C[::3, 1::3] - In []: C[::4, 1:4] - #+end_src * Summary - You should now be able to -- - - Manipulate 1D \& Multi dimensional arrays - - Access and change individual elements - - Access and change rows and columns - - Slice and stride on arrays - - Read images into arrays and manipulate them. + In this tutorial session we learnt + + Obtaining parts of lists using slicing and striding + + List concatenation + + Sorting lists + + Reversing lists + * Thank you! #+begin_latex \begin{block}{} diff -r be96dc6c9743 -r 68813d8d80fb manipulating-lists/slides.tex --- a/manipulating-lists/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/manipulating-lists/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,95 +1,141 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\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} +% Created 2010-11-09 Tue 16:07 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{Manipulating Lists} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + \begin{frame} - \maketitle +\frametitle{Outline} +\label{sec-1} + + In this session we shall be looking at +\begin{itemize} +\item Concatenating lists +\item Obtaining parts of lists +\item Sorting lists +\item Reversing lists +\end{itemize} \end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + Obtain the primes less than 10, from the list \texttt{primes}. +\end{frame} \begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +primes[0:4] +\end{lstlisting} \end{frame} +\begin{frame}[fragile] +\frametitle{Slicing} +\label{sec-4} + +\lstset{language=Python} +\begin{lstlisting} +p[start:stop] +\end{lstlisting} +\begin{itemize} +\item Returns all elements of \texttt{p} between \texttt{start} and \texttt{stop} +\item The element with index equal to \texttt{stop} is \textbf{not} included. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-5} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + Obtain all the multiples of three from the list \texttt{num}. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-6} +\lstset{language=Python} +\begin{lstlisting} +num[::3] +\end{lstlisting} +\end{frame} +\begin{frame}[fragile] +\frametitle{Question 3} +\label{sec-7} + + Given a list of marks of students in an examination, obtain a list + with marks in descending order. +\lstset{language=Python} +\begin{lstlisting} +marks = [99, 67, 47, 100, 50, 75, 62] +\end{lstlisting} +\end{frame} \begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 3} +\label{sec-8} + +\lstset{language=Python} +\begin{lstlisting} +sorted(marks)[::-1] +\end{lstlisting} +OR +\lstset{language=Python} +\begin{lstlisting} +sorted(marks, reverse=True) +\end{lstlisting} \end{frame} - \begin{frame} - \frametitle{Thank you!} +\frametitle{Summary} +\label{sec-9} + + In this tutorial session we learnt +\begin{itemize} +\item Obtaining parts of lists using slicing and striding +\item List concatenation +\item Sorting lists +\item Reversing lists +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-10} + \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r be96dc6c9743 -r 68813d8d80fb matrices/questions.rst --- a/matrices/questions.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/matrices/questions.rst Thu Nov 11 02:28:55 2010 +0530 @@ -3,14 +3,14 @@ .. A mininum of 8 questions here (along with answers) -1. ``matrix(A) * matrix(B)`` and ``array(A) * array(B)`` are the same. +1. ``array(A) * array(B)`` does matrix multiplication. a. True #. False Answer: False -2. ``matrix(A) * array(B)`` does, +2. ``array(A) * array(B)`` does, a. Element wise multiplication. #. Matrix multiplication. @@ -19,9 +19,9 @@ multiplication will be done, otherwise element wise multiplication. -Answer: Matrix multiplication +Answer: Element wise multiplication. -3. A and B are two matrix objects. Element wise multiplication in +3. A and B are two array objects. Element wise multiplication in matrices are done by, a. A * B @@ -29,7 +29,7 @@ #. ``dot(A, B)`` #. ``element_multiply(A,B)`` -Answer: multiply(A, B) +Answer: dot(A, B) 4. ``norm(A)`` method determines the, @@ -50,7 +50,7 @@ 6. The code snippet will work without an error, :: - A = matrix([[1, 2, 3, 4], [5, 6, 7, 8]]) + A = array([[1, 2, 3, 4], [5, 6, 7, 8]]) inv(A) a. True diff -r be96dc6c9743 -r 68813d8d80fb matrices/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/matrices/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,26 @@ +Matrix Multiplication:\\ +{\ex \lstinline| c = dot(a,b)|} + +Transpose of a matrix:\\ +{\ex \lstinline| m.T|} + +Inverse of a matrix:\\ +{\ex \lstinline| im = inv(m)|} + +Frobenius norm of matrix:\\ +{\ex \lstinline| norm(m)|} + +Inverse norm of matrix:\\ +{\ex \lstinline| norm(m, ord=inf)|} + +Determinant of matrix:\\ +{\ex \lstinline| det(m)|} + +Eigen values of matrix:\\ +{\ex \lstinline| eigvals(m)|} + +Eigen vectors of matrix:\\ +{\ex \lstinline| eig(m)[1]|} + +Singular Value Decomposition on matrix m:\\ +{\ex \lstinline| svd(m)|} diff -r be96dc6c9743 -r 68813d8d80fb matrices/script.rst --- a/matrices/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/matrices/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -30,6 +30,7 @@ External Reviewer : Checklist OK? : [2010-10-05] +.. #[punch: please mark the exercises, using the syntax we decided upon.] ======== Matrices @@ -41,9 +42,10 @@ {{{ switch to next slide, outline slide }}} In this tutorial we will learn about matrices, creating matrices using -direct data, by converting a list, matrix operations. Finding inverse -of a matrix, determinant of a matrix, eigen values and eigen vectors -of a matrix, norm and singular value decomposition of matrices. +direct data, by converting a list and matrix operations. Finding +inverse of a matrix, determinant of a matrix, eigen values and eigen +vectors of a matrix, norm and singular value decomposition of +matrices. {{{ creating a matrix }}} @@ -51,7 +53,7 @@ on arrays are valid on matrices also. A matrix may be created as, :: - m1 = matrix([1,2,3,4]) + m1 = array([1,2,3,4]) .. #[Puneeth: don't use ``matrix``. Use ``array``. The whole script will @@ -70,10 +72,16 @@ :: l1 = [[1,2,3,4],[5,6,7,8]] - m2 = matrix(l1) + m2 = array(l1) + +{{{ switch to next slide, exercise 1}}} -Note that all matrix operations are done using arrays, so a matrix may -also be created as +Pause here and create a two dimensional matrix m3 of order 2 by 4 with +elements 5, 6, 7, 8, 9, 10, 11, 12. + +{{{ switch to next slide, solution }}} + +m3 can be created as, :: m3 = array([[5,6,7,8],[9,10,11,12]]) @@ -100,17 +108,16 @@ m3 * m2 -Note that in arrays ``array(A) star array(B)`` does element wise -multiplication and not matrix multiplication, but unlike arrays, the -operation ``matrix(A) star matrix(B)`` does matrix multiplication and -not element wise multiplication. And in this case since the sizes are -not compatible for multiplication it returned an error. +Note that in arrays ``m3 * m2`` does element wise multiplication and not +matrix multiplication, -And element wise multiplication in matrices are done using the -function ``multiply()`` +And matrix multiplication in matrices are done using the function ``dot()`` :: - multiply(m3,m2) + dot(m3, m2) + +but due to size mismatch the multiplication could not be done and it +returned an error, {{{ switch to next slide, Matrix multiplication (cont'd) }}} @@ -126,11 +133,10 @@ the order four by two, :: - m4 = matrix([[1,2],[3,4],[5,6],[7,8]]) - m1 * m4 + m4 = array([[1,2],[3,4],[5,6],[7,8]]) + dot(m1, m4) -thus unlike in array object ``star`` can be used for matrix multiplication -in matrix object. +thus the function ``dot()`` can be used for matrix multiplication. {{{ switch to next slide, recall from arrays }}} @@ -154,11 +160,13 @@ {{{ switch to next slide, Frobenius norm of inverse of matrix }}} +.. #[punch: arange has not been introduced.] + Now let us try to find out the Frobenius norm of inverse of a 4 by 4 matrix, the matrix being, :: - m5 = matrix(arange(1,17).reshape(4,4)) + m5 = arange(1,17).reshape(4,4) print m5 The inverse of a matrix A, A raise to minus one is also called the @@ -173,21 +181,28 @@ im5 = inv(m5) +.. #[punch: we don't need to show this way of calculating the norm, do +.. we? even if we do, we should show it in the "array style". +.. something like: +.. sqrt(sum(each * each))] + And the Frobenius norm of the matrix ``im5`` can be found out as, :: sum = 0 - for each in array(im5.flatten())[0]: + for each in im5.flatten(): sum += each * each print sqrt(sum) {{{ switch to next slide, infinity norm }}} +.. #[punch: similarly for this section.] Now try to find out the infinity norm of the matrix im5. The infinity norm of a matrix is defined as the maximum value of sum of the absolute of elements in each row. Pause here and try to solve the problem yourself. + The solution for the problem is, :: @@ -238,6 +253,9 @@ eig(m5) + +.. #[punch: has the tuple word been introduced?] + Note that it returned a tuple of two matrices. The first element in the tuple are the eigen values and the second element in the tuple are the eigen vectors. Thus the eigen values are, @@ -296,5 +314,5 @@ mode: rst indent-tabs-mode: nil sentence-end-double-space: nil - fill-column: 75 + fill-column: 70 End: diff -r be96dc6c9743 -r 68813d8d80fb matrices/slides.org --- a/matrices/slides.org Mon Nov 08 02:12:28 2010 +0530 +++ b/matrices/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -42,11 +42,16 @@ * Creating a matrix - Creating a matrix using direct data - : In []: m1 = matrix([1, 2, 3, 4]) + : In []: m1 = array([1, 2, 3, 4]) - Creating a matrix using lists : In []: l1 = [[1,2,3,4],[5,6,7,8]] - : In []: m2 = matrix(l1) - - A matrix is basically an array + : In []: m2 = array(l1) +* Exercise 1 + Create a (2, 4) matrix ~m3~ + : m3 = [[5, 6, 7, 8], + : [9, 10, 11, 12]] +* Solution 1 + - m3 can be created as, : In []: m3 = array([[5,6,7,8],[9,10,11,12]]) * Matrix operations @@ -55,20 +60,20 @@ - Element-wise subtraction (both matrix should be of order ~mXn~) : In []: m3 - m2 * Matrix Multiplication - - Matrix Multiplication + - Element-wise multiplication using ~m3 * m2~ : In []: m3 * m2 + - Matrix Multiplication using ~dot(m3, m2)~ + : In []: dot(m3, m2) : Out []: ValueError: objects are not aligned - - Element-wise multiplication using ~multiply()~ - : multiply(m3, m2) * Matrix Multiplication (cont'd) - Create two compatible matrices of order ~nXm~ and ~mXr~ : In []: m1.shape - matrix m1 is of order ~1 X 4~ - Creating another matrix of order ~4 X 2~ - : In []: m4 = matrix([[1,2],[3,4],[5,6],[7,8]]) + : In []: m4 = array([[1,2],[3,4],[5,6],[7,8]]) - Matrix multiplication - : In []: m1 * m4 + : In []: dot(m1, m4) * Recall from ~array~ - The functions - ~identity(n)~ - @@ -86,11 +91,11 @@ * More matrix operations Transpose of a matrix : In []: m4.T -* Exercise 1 : Frobenius norm \& inverse +* Exercise 2 : Frobenius norm \& inverse Find out the Frobenius norm of inverse of a ~4 X 4~ matrix. : The matrix is - : m5 = matrix(arange(1,17).reshape(4,4)) + : m5 = arange(1,17).reshape(4,4) - Inverse of A, - #+begin_latex @@ -102,7 +107,7 @@ $||A||_F = [\sum_{i,j} abs(a_{i,j})^2]^{1/2}$ #+end_latex -* Exercise 2: Infinity norm +* Exercise 3 : Infinity norm Find the infinity norm of the matrix ~im5~ : - Infinity norm is defined as, diff -r be96dc6c9743 -r 68813d8d80fb matrices/slides.tex --- a/matrices/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/matrices/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,4 +1,4 @@ -% Created 2010-10-12 Tue 14:28 +% Created 2010-11-07 Sun 16:18 \documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} \usepackage[T1]{fontenc} @@ -70,7 +70,7 @@ \end{itemize} \begin{verbatim} - In []: m1 = matrix([1, 2, 3, 4]) + In []: m1 = array([1, 2, 3, 4]) \end{verbatim} \begin{itemize} @@ -79,11 +79,25 @@ \begin{verbatim} In []: l1 = [[1,2,3,4],[5,6,7,8]] - In []: m2 = matrix(l1) + In []: m2 = array(l1) \end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 1} +\label{sec-3} + + Create a (2, 4) matrix \texttt{m3} +\begin{verbatim} + m3 = [[5, 6, 7, 8], + [9, 10, 11, 12]] +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-4} \begin{itemize} -\item A matrix is basically an array +\item m3 can be created as, \end{itemize} \begin{verbatim} @@ -92,7 +106,7 @@ \end{frame} \begin{frame}[fragile] \frametitle{Matrix operations} -\label{sec-3} +\label{sec-5} \begin{itemize} \item Element-wise addition (both matrix should be of order \texttt{mXn}) @@ -109,25 +123,25 @@ \end{frame} \begin{frame}[fragile] \frametitle{Matrix Multiplication} -\label{sec-4} +\label{sec-6} \begin{itemize} -\item Matrix Multiplication +\item Element-wise multiplication using \texttt{m3 * m2} \begin{verbatim} In []: m3 * m2 - Out []: ValueError: objects are not aligned \end{verbatim} -\item Element-wise multiplication using \texttt{multiply()} +\item Matrix Multiplication using \texttt{dot(m3, m2)} \begin{verbatim} - multiply(m3, m2) + In []: dot(m3, m2) + Out []: ValueError: objects are not aligned \end{verbatim} \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Matrix Multiplication (cont'd)} -\label{sec-5} +\label{sec-7} \begin{itemize} \item Create two compatible matrices of order \texttt{nXm} and \texttt{mXr} @@ -142,19 +156,19 @@ \item Creating another matrix of order \texttt{4 X 2} \begin{verbatim} - In []: m4 = matrix([[1,2],[3,4],[5,6],[7,8]]) + In []: m4 = array([[1,2],[3,4],[5,6],[7,8]]) \end{verbatim} \item Matrix multiplication \begin{verbatim} - In []: m1 * m4 + In []: dot(m1, m4) \end{verbatim} \end{itemize} \end{frame} \begin{frame} \frametitle{Recall from \texttt{array}} -\label{sec-6} +\label{sec-8} \begin{itemize} \item The functions @@ -178,7 +192,7 @@ \end{frame} \begin{frame}[fragile] \frametitle{More matrix operations} -\label{sec-7} +\label{sec-9} Transpose of a matrix \begin{verbatim} @@ -186,8 +200,8 @@ \end{verbatim} \end{frame} \begin{frame}[fragile] -\frametitle{Exercise 1 : Frobenius norm \& inverse} -\label{sec-8} +\frametitle{Exercise 2 : Frobenius norm \& inverse} +\label{sec-10} Find out the Frobenius norm of inverse of a \texttt{4 X 4} matrix. \begin{verbatim} @@ -196,7 +210,7 @@ The matrix is \begin{verbatim} - m5 = matrix(arange(1,17).reshape(4,4)) + m5 = arange(1,17).reshape(4,4) \end{verbatim} \begin{itemize} @@ -215,8 +229,8 @@ \end{itemize} \end{frame} \begin{frame}[fragile] -\frametitle{Exercise 2: Infinity norm} -\label{sec-9} +\frametitle{Exercise 3 : Infinity norm} +\label{sec-11} Find the infinity norm of the matrix \texttt{im5} \begin{verbatim} @@ -230,7 +244,7 @@ \end{frame} \begin{frame}[fragile] \frametitle{\texttt{norm()} method} -\label{sec-10} +\label{sec-12} \begin{itemize} \item Frobenius norm @@ -247,7 +261,7 @@ \end{frame} \begin{frame}[fragile] \frametitle{Determinant} -\label{sec-11} +\label{sec-13} Find out the determinant of the matrix m5 \begin{verbatim} @@ -265,7 +279,7 @@ \end{frame} \begin{frame}[fragile] \frametitle{eigen values \& eigen vectors} -\label{sec-12} +\label{sec-14} Find out the eigen values and eigen vectors of the matrix \texttt{m5}. \begin{verbatim} @@ -300,7 +314,7 @@ \end{frame} \begin{frame}[fragile] \frametitle{Singular Value Decomposition (\texttt{svd})} -\label{sec-13} +\label{sec-15} $M = U \Sigma V^*$ \begin{itemize} @@ -318,7 +332,7 @@ \end{frame} \begin{frame} \frametitle{Summary} -\label{sec-14} +\label{sec-16} \begin{itemize} \item Matrices @@ -337,7 +351,7 @@ \end{frame} \begin{frame} \frametitle{Thank you!} -\label{sec-15} +\label{sec-17} \begin{block}{} \begin{center} diff -r be96dc6c9743 -r 68813d8d80fb other-type-of-plots/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other-type-of-plots/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,11 @@ +Creating scatter plot:\\ +{\ex \lstinline| scatter(x, y)|} + +Creating pie chart:\\ +{\ex \lstinline| pie(p, labels=l)|} + +Creating bar chart:\\ +{\ex \lstinline| bar(x, y)|} + +Creating log-log chart:\\ +{\ex \lstinline| loglog(x, y)|} diff -r be96dc6c9743 -r 68813d8d80fb outline_and_allocations.rst --- a/outline_and_allocations.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/outline_and_allocations.rst Thu Nov 11 02:28:55 2010 +0530 @@ -447,7 +447,7 @@ 8 Module 8: Python Language: Advanced (16) ========================================== -8.1 LO: getting started with functions (3) [nishanth] +8.1 LO: getting started with functions (3) [anoop] ----------------------------------------------------- * defining function * arguments diff -r be96dc6c9743 -r 68813d8d80fb plotting-data/questions.rst --- a/plotting-data/questions.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/plotting-data/questions.rst Thu Nov 11 02:28:55 2010 +0530 @@ -19,14 +19,22 @@ -3. How do you plot points ? +3. How do you plot the data as points using plot function? By passing an extra parameter '.'. -4. What does the parameter 'o' do ? +.. #[[Anoop: It can better if asked as, How do you plot the data as + points using plot function?]] + +4. Can you comment about the result of this plot command . + plot(x, y,'o') + It plots large points. +.. #[[Anoop: give an example and ask what it does, like plot(x, y, + 'o'), that makes the question simple]] + 5. How do you plot error in Python? Using the function error bar. diff -r be96dc6c9743 -r 68813d8d80fb plotting-data/script.rst --- a/plotting-data/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/plotting-data/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -16,38 +16,51 @@ .. Author : Amit - Internal Reviewer : + Internal Reviewer : Anoop Jacob Thomas External Reviewer : Checklist OK? : [2010-10-05] +.. #[[Anoop: Add quickref]] +.. #[[Anoop: Slides are incomplete, add summary slide, thank you slide + etc.]] + +=============================== Plotting Experimental Data -============================= +=============================== + +{{{ Show the slide containing title }}} + Hello and welcome , this tutorial on Plotting Experimental data is presented by the fossee team. -{{{ Show the slide containing title }}} +{{{ Show the Outline Slide }}} - -{{{ Show the Outline Slide }}} +.. #[[Anoop: outline slide is missing]] Here we will discuss plotting Experimental data. 1. We will see how we can represent a sequence of numbers in Python. -2. We will also become fimiliar with elementwise squaring of such a +2. We will also become familiar with elementwise squaring of such a sequence. -3. We will also see how we can use our graph to indicate Error. +3. How to plot data points using python. -One needs to be fimiliar with the concepts of plotting +4. We will also see how we can use our graph to indicate Error. + +One needs to be familiar with the concepts of plotting mathematical functions in Python. -We will use data from a Simple Pendulum Experiment to illustrate our -points. +We will use data from a Simple Pendulum Experiment to illustrate. + +.. #[[Anoop: what do you mean by points here? if you mean the + points/numbered list in outline slide, then remove the usage point + from here.]] {{{ Simple Pendulum data Slide }}} - +.. #[[Anoop: slides are incomplete, work on slides and context + switches]] As we know for a simple pendulum length,L is directly proportional to @@ -55,104 +68,151 @@ First we will have to initiate L and T values. We initiate them as sequence -of values. To tell ipython a sequence of values we write the sequence in -comma seperated values inside two square brackets. This is also called List -so to create two sequences +of values. We define a sequence by comma seperated values inside two square brackets. +This is also called List.Lets create two sequences L and t. -L,t type in ipython shell. :: +.. #[[Anoop: instead of saying "to tell ipython a sequence of values" + and make it complicated, we can tell, we define a sequence as]] + +.. #[[Anoop: sentence is incomplete, can be removed]] - In []: L = [0.1, 0.2, 0.3, 0.4, 0.5,0.6, 0.7, 0.8, 0.9] - - In []: t= [0.69, 0.90, 1.19,1.30, 1.47, 1.58, 1.77, 1.83, 1.94] +{{{ Show the initializing L&T slide }}} + +Type in ipython shell :: + L = [0.1, 0.2, 0.3, 0.4, 0.5,0.6, 0.7, 0.8, 0.9] + + t= [0.69, 0.90, 1.19,1.30, 1.47, 1.58, 1.77, 1.83, 1.94] - -To obtain the square of sequence t we will use the function square + +To obtain the square of sequence t we will use the function square with argument t.This is saved into the variable tsquare.:: - In []: tsquare=square(t) - + tsquare=square(t) + tsqaure array([ 0.4761, 0.81 , 1.4161, 1.69 , 2.1609, 2.4964, 3.1329, 3.3489, 3.7636]) +.. #[[Anoop: how do you get the array([ 0.4761 ....]) output?]] + Now to plot L vs T^2 we will simply type :: - In []: plot(L,t,.) + plot(L,tsquare,'.') + +.. #[[Anoop: be consistent with the spacing and all.]] '.' here represents to plot use small dots for the point. :: - In []: clf() + clf() You can also specify 'o' for big dots.:: - In []: plot(L,t,o) + plot(L,tsquare,'o') - In []: clf() + clf() -{{{ Slide with Error data included }}} +Following are exercises that you must do. + +%% %% Plot the given experimental data with large dots.The data is +on your screen. + +%% %% Plot the given experimental data with small dots. +The data is on your screen + + +Please, pause the video here. Do the exercises and then continue. + + + -Now we shall try and take into account error into our plots . The -Error values for L and T are on your screen.We shall again intialize -the sequence values in the same manner as we did for L and t :: +.. #[[Anoop: Make sure code is correct, corrected plot(L,t,o) to + plot(L,t,'o')]] - In []: delta_L= [0.08,0.09,0.07,0.05,0.06,0.00,0.06,0.06,0.01] - - In []: delta_T= [0.04,0.08,0.11,0.05,0.03,0.03,0.01,0.07,0.01] +.. #[[Anoop: again slides are incomplete.]] + +For any experimental there is always an error in measurements due to +instrumental and human constaraints.Now we shall try and take into +account error into our plots . The Error values for L and T are on +your screen.We shall again intialize the sequence values in the same +manner as we did for L and t + +The error data we will use is on your screen. + +{{{ Show the Adding Error Slide }}} +.. #[[Anoop: give introduction to error and say what we are going to + do]] + +:: + + delta_L= [0.08,0.09,0.07,0.05,0.06,0.00,0.06,0.06,0.01] + delta_T= [0.04,0.08,0.03,0.05,0.03,0.03,0.04,0.07,0.08] Now to plot L vs T^2 with an error bar we use the function errorbar() The syntax of the command is as given on the screen. :: - In []: errorbar(L,tsquare,xerr=delta_L, yerr=delta_T, fmt='b.') + errorbar(L,tsquare,xerr=delta_L, yerr=delta_T, fmt='b.') -This gives a plot with error bar for x and y axis. The dots are of blue color. The parameters xerr and yerr are error on x and y axis and fmt is the format of the plot. +This gives a plot with error bar for x and y axis. The dots are of +blue color. The parameters xerr and yerr are error on x and y axis and +fmt is the format of the plot. -similarly we can draw the same error bar with big red dots just change +similarly we can draw the same error bar with big red dots just change the parameters to fmt to 'ro'. :: - In []: clf() - In []: errorbar(L,tsquare,xerr=delta_L, yerr=delta_T, fmt='ro') + clf() + errorbar(L,tsquare,xerr=delta_L, yerr=delta_T, fmt='ro') thats it. you can explore other options to errorbar using the documentation of errorbar.:: - In []: errorbar? + errorbar? + +Following is an exercise that you must do. + +%% %% Plot the given experimental data with large green dots.Also include +the error in your plot. + +Please, pause the video here. Do the exercise and then continue. + + + + + -{{{ Summary Slides }}} +{{{ Show Summary Slide }}} -In this tutorial we have learnt : +In this tutorial we have learnt : -1. How to declare a sequence of number , specifically the kind of sequence we learned was a list. + -2. Plotting experimental data extending our knowledge from mathematical functions. +1. How to declare a sequence of numbers. + +2. Plotting experimental data. -3. The various options available for plotting dots instead of lines. +#. The various options available for plotting dots instead of lines. -4. Plotting experimental data such that we can also represent error. We did this using the errorbar() function. +#. Plotting experimental data such that we can also represent error. + {{{ Show the "sponsored by FOSSEE" slide }}} - +.. #[[Anoop: again slides are incomplete]] This tutorial was created as a part of FOSSEE project. Hope you have enjoyed and found it useful. - Thankyou - - +Thank You! -Author : Amit Sethi -Internal Reviewer : -Internal Reviewer 2 : diff -r be96dc6c9743 -r 68813d8d80fb plotting-data/slides.org --- a/plotting-data/slides.org Mon Nov 08 02:12:28 2010 +0530 +++ b/plotting-data/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -2,26 +2,40 @@ #+LaTeX_CLASS_OPTIONS: [presentation] #+BEAMER_FRAME_LEVEL: 1 -#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} #+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) #+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC -#+OPTIONS: H:5 num:t toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} #+TITLE: Plotting Experimental Data #+AUTHOR: FOSSEE #+DATE: 2010-09-14 Tue #+EMAIL: info@fossee.in -# \author[FOSSEE] {FOSSEE} - -# \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -# \date{} +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc -* Tutorial Plan -** Plotting Experiment Data and Error Bars -* Pre-requisites -** Plotting simple analytical Functions -* plot L vs. T^2 +* Outline + - Defining sequence of numbers + - Squaring sequence of numbers + - Plotting Data Points + - Indicating Error through Errorbars + +* Simple Pendulum Data #+ORGTBL: L vs T^2 orgtbl-to-latex @@ -36,46 +50,151 @@ | 0.8 | 1.83 | | 0.9 | 1.94 | - - * Initializing L & T - : In []: L = [0.1, 0.2, 0.3, 0.4, 0.5, - : 0.6, 0.7, 0.8, 0.9] - : In []: t = [0.69, 0.90, 1.19, - : 1.30, 1.47, 1.58, - : 1.77, 1.83, 1.94] -* square() - : In []: tsquare=square(t) - - : array([ 0.4761, 0.81 , 1.4161, 1.69 , 2.1609, 2.4964, 3.1329, - : 3.3489, 3.7636]) + : L = [0.1, 0.2, 0.3, 0.4, 0.5, + : 0.6, 0.7, 0.8, 0.9] + : t = [0.69, 0.90, 1.19, + : 1.30, 1.47, 1.58, + : 1.77, 1.83, 1.94] - -* Plotting - : In[]: plot(L,t,.) + + +* Question 1 + - Plot the given experimental data with large dots. + The data is on your screen. - : In[]: plot(L,t,o) +* Question 1 Data + +#+ORGTBL: L vs T^2 orgtbl-to-latex + + + | S | n | + | 0.19 | 10.74 | + | 0.38 | 14.01 | + | 0.57 | 18.52 | + | 0.77 | 20.23 | + | 0.96 | 22.88 | + | 1.15 | 24.59 | + | 1.34 | 27.55 | + | 1.54 | 28.48 | + | 1.73 | 30.20 | + + +* Solution 1 + + : S=[0.19,0.38,0.57,0.77,0.96, + : 1.15,1.34,1.54,1.73] + : n=[10.74,14.01,18.52,20.23, + : 22.88,24.59,27.55,28.48,30.20] + : plot(S,n,'o') + +* Question 2 + - Plot the given experimental data with small dots. + The data is on your screen. + +* Question 2 Data + +#+ORGTBL: L vs T^2 orgtbl-to-latex + + | P | D | + | 1.48 | 0.68 | + | 2.96 | 0.89 | + | 4.44 | 1.18 | + | 5.92 | 1.29 | + | 7.40 | 1.46 | + | 8.88 | 1.57 | + | 10.3 | 1.76 | + | 11.8 | 1.82 | + | 13.3 | 1.93 | + +* Solution 2 + + : P=[1.48,2.96,4.44,5.92,7.40, + : 8.88,10.3,11.8,13.3] + : D=[0.68,0.89,1.18,1.29,1.46, + : 1.57,1.76,1.82,1.93] + : plot(P,D,'.') * Adding Error +#+ORGTBL: L vs T^2 orgtbl-to-latex - | L | T | /Delta L | /Delta T | + | L | T | \delta L | \delta T | | 0.1 | 0.69 | 0.08 | 0.04 | | 0.2 | 0.90 | 0.09 | 0.08 | - | 0.3 | 1.19 | 0.07 | 0.11 | + | 0.3 | 1.19 | 0.07 | 0.03 | | 0.4 | 1.30 | 0.05 | 0.05 | | 0.5 | 1.47 | 0.06 | 0.03 | | 0.6 | 1.58 | 0.00 | 0.03 | - | 0.7 | 1.77 | 0.06 | 0.01 | + | 0.7 | 1.77 | 0.06 | 0.04 | | 0.8 | 1.83 | 0.06 | 0.07 | - | 0.9 | 1.94 | 0.01 | 0.01 | + | 0.9 | 1.94 | 0.01 | 0.08 | * Plotting Error bar - : In[]: errorbar(L,tsquare,xerr=delta_L, yerr=delta_T, - : fmt='b.') + : errorbar(L,tsquare,xerr=delta_L, yerr=delta_T, + : fmt='b.') +* Question 1 + + - Plot the given experimental data with large green dots.Also include + the error in your plot. + + +* Question 1 Data + + #+ORGTBL: L vs T^2 orgtbl-to-latex + + | S | n | \delta S | \delta n | + | 0.19 | 10.74 | 0.006 | 0.61 | + | 0.38 | 14.01 | 0.006 | 0.69 | + | 0.57 | 18.52 | 0.005 | 0.53 | + | 0.77 | 20.23 | 0.003 | 0.38 | + | 0.96 | 22.88 | 0.004 | 0.46 | + | 1.15 | 24.59 | 0.007 | 0.37 | + | 1.34 | 27.55 | 0.004 | 0.46 | + | 1.54 | 28.48 | 0.004 | 0.46 | + | 1.73 | 30.20 | 0.007 | 0.37 | + + + + +* Solution 1 + + : S=[0.19,0.38,0.57,0.77,0.96, + : 1.15,1.34,1.54,1.73] + : n=[10.74,14.01,18.52,20.23, + : 22.88,24.59,27.55,28.48,30.20] + : delta_S=[0.006,0.006,0.005,0.003, + : 0.004,0.007,0.004,0.004,0.007] + : delta_n=[0.61,0.69,0.53,0.38,0.46, + : 0.37,0.46,0.46,0.37] + : errorbar(S,n,xerr=delta_S, yerr=delta_n, + : fmt='go') + +* Summary + : L = [0.1, 0.2, 0.3, 0.4, 0.5, + : 0.6, 0.7, 0.8, 0.9] + : plot(x,y,'o') + : plot(x,y,'.') +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + + diff -r be96dc6c9743 -r 68813d8d80fb plotting-data/slides.tex --- a/plotting-data/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/plotting-data/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,21 +1,34 @@ -% Created 2010-10-28 Thu 15:05 +% Created 2010-11-10 Wed 02:09 \documentclass[presentation]{beamer} -\usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} \usepackage[latin1]{inputenc} \usepackage[T1]{fontenc} +\usepackage{fixltx2e} \usepackage{graphicx} \usepackage{longtable} \usepackage{float} \usepackage{wrapfig} \usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} \usepackage{amssymb} \usepackage{hyperref} - +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} \title{Plotting Experimental Data} \author{FOSSEE} \date{2010-09-14 Tue} +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} \maketitle @@ -25,27 +38,23 @@ + + + \begin{frame} -\frametitle{Tutorial Plan} +\frametitle{Outline} \label{sec-1} + \begin{itemize} - -\item Plotting Experiment Data and Error Bars\\ -\label{sec-1.1}% -\end{itemize} % ends low level +\item Defining sequence of numbers +\item Squaring sequence of numbers +\item Plotting Data Points +\item Indicating Error through Errorbars +\end{itemize} \end{frame} \begin{frame} -\frametitle{Pre-requisites} +\frametitle{Simple Pendulum Data} \label{sec-2} -\begin{itemize} - -\item Plotting simple analytical Functions\\ -\label{sec-2.1}% -\end{itemize} % ends low level -\end{frame} -\begin{frame} -\frametitle{plot L vs. T$^2$} -\label{sec-3} @@ -67,70 +76,136 @@ - \end{frame} \begin{frame}[fragile] \frametitle{Initializing L \& T} -\label{sec-4} +\label{sec-3} \begin{verbatim} - In []: L = [0.1, 0.2, 0.3, 0.4, 0.5, - 0.6, 0.7, 0.8, 0.9] - In []: t = [0.69, 0.90, 1.19, - 1.30, 1.47, 1.58, - 1.77, 1.83, 1.94] + L = [0.1, 0.2, 0.3, 0.4, 0.5, + 0.6, 0.7, 0.8, 0.9] + t = [0.69, 0.90, 1.19, + 1.30, 1.47, 1.58, + 1.77, 1.83, 1.94] \end{verbatim} \end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-4} + +\begin{itemize} +\item Plot the given experimental data with large dots. +\end{itemize} + + The data is on your screen. + +\end{frame} +\begin{frame} +\frametitle{Question 1 Data} +\label{sec-5} + + + + + +\begin{center} +\begin{tabular}{rr} + S & n \\ + 0.19 & 10.74 \\ + 0.38 & 14.01 \\ + 0.57 & 18.52 \\ + 0.77 & 20.23 \\ + 0.96 & 22.88 \\ + 1.15 & 24.59 \\ + 1.34 & 27.55 \\ + 1.54 & 28.48 \\ + 1.73 & 30.20 \\ +\end{tabular} +\end{center} + + + +\end{frame} \begin{frame}[fragile] -\frametitle{square()} -\label{sec-5} +\frametitle{Solution 1} +\label{sec-6} + \begin{verbatim} - In []: tsquare=square(t) + S=[0.19,0.38,0.57,0.77,0.96, + 1.15,1.34,1.54,1.73] + n=[10.74,14.01,18.52,20.23, + 22.88,24.59,27.55,28.48,30.20] + plot(S,n,'o') \end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-7} + +\begin{itemize} +\item Plot the given experimental data with small dots. +\end{itemize} - -\begin{verbatim} - array([ 0.4761, 0.81 , 1.4161, 1.69 , 2.1609, 2.4964, 3.1329, - 3.3489, 3.7636]) -\end{verbatim} + The data is on your screen. +\end{frame} +\begin{frame} +\frametitle{Question 2 Data} +\label{sec-8} + + + + +\begin{center} +\begin{tabular}{rr} + P & D \\ + 1.48 & 0.68 \\ + 2.96 & 0.89 \\ + 4.44 & 1.18 \\ + 5.92 & 1.29 \\ + 7.40 & 1.46 \\ + 8.88 & 1.57 \\ + 10.3 & 1.76 \\ + 11.8 & 1.82 \\ + 13.3 & 1.93 \\ +\end{tabular} +\end{center} \end{frame} \begin{frame}[fragile] -\frametitle{Plotting} -\label{sec-6} +\frametitle{Solution 2} +\label{sec-9} + \begin{verbatim} - In[]: plot(L,t,.) -\end{verbatim} - - - -\begin{verbatim} - In[]: plot(L,t,o) + P=[1.48,2.96,4.44,5.92,7.40, + 8.88,10.3,11.8,13.3] + D=[0.68,0.89,1.18,1.29,1.46, + 1.57,1.76,1.82,1.93] + plot(P,D,'.') \end{verbatim} \end{frame} \begin{frame} \frametitle{Adding Error} -\label{sec-7} +\label{sec-10} \begin{center} \begin{tabular}{rrrr} - L & T & /Delta L & /Delta T \\ - 0.1 & 0.69 & 0.08 & 0.04 \\ - 0.2 & 0.90 & 0.09 & 0.08 \\ - 0.3 & 1.19 & 0.07 & 0.11 \\ - 0.4 & 1.30 & 0.05 & 0.05 \\ - 0.5 & 1.47 & 0.06 & 0.03 \\ - 0.6 & 1.58 & 0.00 & 0.03 \\ - 0.7 & 1.77 & 0.06 & 0.01 \\ - 0.8 & 1.83 & 0.06 & 0.07 \\ - 0.9 & 1.94 & 0.01 & 0.01 \\ + L & T & $\delta$ L & $\delta$ T \\ + 0.1 & 0.69 & 0.08 & 0.04 \\ + 0.2 & 0.90 & 0.09 & 0.08 \\ + 0.3 & 1.19 & 0.07 & 0.03 \\ + 0.4 & 1.30 & 0.05 & 0.05 \\ + 0.5 & 1.47 & 0.06 & 0.03 \\ + 0.6 & 1.58 & 0.00 & 0.03 \\ + 0.7 & 1.77 & 0.06 & 0.04 \\ + 0.8 & 1.83 & 0.06 & 0.07 \\ + 0.9 & 1.94 & 0.01 & 0.08 \\ \end{tabular} \end{center} @@ -140,13 +215,99 @@ \end{frame} \begin{frame}[fragile] \frametitle{Plotting Error bar} -\label{sec-8} +\label{sec-11} \begin{verbatim} - In[]: errorbar(L,tsquare,xerr=delta_L, yerr=delta_T, - fmt='b.') + errorbar(L,tsquare,xerr=delta_L, yerr=delta_T, + fmt='b.') \end{verbatim} \end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-12} + + +\begin{itemize} +\item Plot the given experimental data with large green dots.Also include +\end{itemize} + + the error in your plot. + + +\end{frame} +\begin{frame} +\frametitle{Question 1 Data} +\label{sec-13} + + + \#+ORGTBL: L vs T$^2$ orgtbl-to-latex + + +\begin{center} +\begin{tabular}{rrrr} + S & n & $\delta$ S & $\delta$ n \\ + 0.19 & 10.74 & 0.006 & 0.61 \\ + 0.38 & 14.01 & 0.006 & 0.69 \\ + 0.57 & 18.52 & 0.005 & 0.53 \\ + 0.77 & 20.23 & 0.003 & 0.38 \\ + 0.96 & 22.88 & 0.004 & 0.46 \\ + 1.15 & 24.59 & 0.007 & 0.37 \\ + 1.34 & 27.55 & 0.004 & 0.46 \\ + 1.54 & 28.48 & 0.004 & 0.46 \\ + 1.73 & 30.20 & 0.007 & 0.37 \\ +\end{tabular} +\end{center} + + + + + +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-14} + + +\begin{verbatim} + S=[0.19,0.38,0.57,0.77,0.96, + 1.15,1.34,1.54,1.73] + n=[10.74,14.01,18.52,20.23, + 22.88,24.59,27.55,28.48,30.20] + delta_S=[0.006,0.006,0.005,0.003, + 0.004,0.007,0.004,0.004,0.007] + delta_n=[0.61,0.69,0.53,0.38,0.46, + 0.37,0.46,0.46,0.37] + errorbar(S,n,xerr=delta_S, yerr=delta_n, + fmt='go') +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Summary} +\label{sec-15} + +\begin{verbatim} + L = [0.1, 0.2, 0.3, 0.4, 0.5, + 0.6, 0.7, 0.8, 0.9] + plot(x,y,'o') + plot(x,y,'.') +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-16} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} \end{document} diff -r be96dc6c9743 -r 68813d8d80fb plotui/buttons.png Binary file plotui/buttons.png has changed diff -r be96dc6c9743 -r 68813d8d80fb plotui/move.png Binary file plotui/move.png has changed diff -r be96dc6c9743 -r 68813d8d80fb plotui/questions.rst --- a/plotui/questions.rst Mon Nov 08 02:12:28 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,51 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. Create 100 equally spaced points between -pi/2 and pi/2? - - Answer: linspace(-pi/2,pi/2,100) - -2. How do you clear a figure in ipython? - - Answer: clf() - -3. How do find the length of a sequence? - - Answer: len(sequence_name) - -4. Create a plot of x and e^x where x is 100 equally spaced points between 0,pi. Hint: e^x -> exp(x) for ipython - - Answer: x=linspace(0,pi,100) - plot(x,exp(x)) - -5. List four formats in which you can save a plot in ipython? - - Answer: png,eps,pdf,ps - -6. List the kind of buttons available in plotui to study the plot better ? - - Zoom button to Zoom In to a region. - Pan button to move it around. - -7. What are the left and right arrow buttons for? - - Answer: These buttons take you to the states that the plot has been. Much like a browser left and right arrow button. - - - -8. What is the home button for in the Plot UI? - - Initial State of the plot. - - - - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Use '?' and explain the similarities and difference between linpace and logspace? -2. Describe one by one all the buttons in UI of plot and their meaning? diff -r be96dc6c9743 -r 68813d8d80fb plotui/quickref.tex --- a/plotui/quickref.tex Mon Nov 08 02:12:28 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,14 +0,0 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} - -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} - -Saving Plot\\ -{\includegraphics[width=60mm]{save.png}} - -Zooming into a part of the plot\\ -{\includegraphics[width=60mm]{zoom.png}} - -Move the plot\\ -{\includegraphics[width=60mm]{move.png}} diff -r be96dc6c9743 -r 68813d8d80fb plotui/save.png Binary file plotui/save.png has changed diff -r be96dc6c9743 -r 68813d8d80fb plotui/script.rst --- a/plotui/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,212 +0,0 @@ -.. Objectives -.. ---------- - -.. By the end of this tutorial you will -- - -.. 1. Create simple plots of mathematical functions -.. #. Use the Figure window to study plots better - - - -.. Prerequisites -.. ------------- - -.. Installation of required tools -.. Ipython - -.. Author : Amit Sethi - Internal Reviewer : - External Reviewer : - Checklist OK? : [2010-10-05] - -Script -------- - - -Hello and welcome to the tutorial on creating simple plots using -Python.This tutorial is presented by the Fossee group. -{{{ Show the Title Slide }}} - -I hope you have IPython running on your computer. - -In this tutorial we will look at plot command and also how to study -the plot using the UI. - -{{{ Show Outline Slide }}} - -Lets start ipython on your shell, type :: - - $ipython -pylab - - -Pylab is a python library which provides plotting functionality.It -also provides many other important mathematical and scientific -functions. After running IPython -pylab in your shell if at the top of -the result of this command, you see something like :: - - - `ERROR: matplotlib could NOT be imported! Starting normal - IPython.` - - -{{{ Slide with Error written on it }}} - - - - -Then you have to install matplotlib and run this command again. - -Now type in your ipython shell :: - - In[]: linpace? - - - -as the documentation says, it returns `num` evenly spaced samples, -calculated over the interval start and stop. To illustrate this, lets -do it form 1 to 100 and try 100 points. :: - - In[]: linspace(1,100,100) - -As you can see a sequence of numbers from 1 to 100 appears. - -Now lets try 200 points between 0 and 1 you do this by typing :: - - - In[]: linspace(0,1,200) - -0 for start , 1 for stop and 200 for no of points. In linspace -the start and stop points can be integers, decimals , or -constants. Let's try and get 100 points between -pi to pi. Type :: - - In[]: p = linspace(-pi,pi,100) - - -'pi' here is constant defined by pylab. Save this to the variable, p -. - -If you now :: - - In[]: len(p) - -You will get the no. of points. len function gives the no of elements -of a sequence. - - -Let's try and plot a cosine curve between -pi and pi using these -points. Simply type :: - - - In[]: plot(p,cos(points)) - -Here cos(points) gets the cosine value at every corresponding point to -p. - - -We can also save cos(points) to variable cosine and plot it using -plot.:: - - In[]: cosine=cos(points) - - In[]: plot(p,cosine) - - - -Now do :: - - In[]: clf() - -this will clear the plot. - -This is done because any other plot we try to make shall come on the -same drawing area. As we do not wish to clutter the area with -overlaid plots , we just clear it with clf(). Now lets try a sine -plot. :: - - - In []: plot(p,sin(p)) - - - - -The Window on which the plot appears can be used to study it better. - -{{{ Show the slide with all the buttons on it }}} - -First of all moving the mouse around gives us the point where mouse -points at. - -Also we have some buttons the right most among them is -for saving the file. - -Just click on it specifying the name of the file. We will save the plot -by the name sin_curve in pdf format. - - - -{{{ Action corelating with the words }}} - -As you can see I can specify format of file from the dropdown. - -Formats like png ,eps ,pdf, ps are available. - -Left to the save button is the slider button to specify the margins. - -{{{ Action corelating with the words }}} - -Left to this is zoom button to zoom into the plot. Just specify the -region to zoom into. -The button left to it can be used to move the axes of the plot. - -{{{ Action corelating with the words }}} - -The next two buttons with a left and right arrow icons change the state of the -plot and take it to the previous state it was in. It more or less acts like a -back and forward button in the browser. - -{{{ Action corelating with the words }}} - -The last one is 'home' referring to the initial plot. - -{{{ Action corelating with the words}}} - - - -{{{ Summary Slide }}} - - -In this tutorial we have looked at - -1. Starting Ipython with pylab - -2. Using linspace function to create `num` equaly spaced points in a region. - -3. Finding length of sequnces using len. - -4. Plotting mathematical functions using plot. - -4. Clearing drawing area using clf - -5. Using the UI of plot for studying it better . Using functionalities like save , zoom and moving the plots on x and y axis - - - - - -{{{ Show the "sponsored by FOSSEE" slide }}} - - - -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - - - - Hope you have enjoyed and found it useful. - - Thankyou - - - -Author : Amit Sethi -Internal Reviewer : -Internal Reviewer 2 : diff -r be96dc6c9743 -r 68813d8d80fb plotui/slides.tex --- a/plotui/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,71 +0,0 @@ -% Created 2010-10-20 Wed 21:57 -\documentclass[presentation]{beamer} -\usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} -\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\usepackage{graphicx} -\usepackage{longtable} -\usepackage{float} -\usepackage{wrapfig} -\usepackage{soul} -\usepackage{amssymb} -\usepackage{hyperref} - - -\title{Plotting Data } -\author{FOSSEE} -\date{2010-09-14 Tue} - -\begin{document} - -\maketitle - -\begin{frame} -\frametitle{Tutorial Plan} -\label{sec-1} -\begin{itemize} - -\item Creating a simple plot\\ -\label{sec-1.1}% -\item Use the buttons on window to study the plot\\ -\label{sec-1.2}% -\end{itemize} % ends low level -\end{frame} -\begin{frame} -\frametitle{Error if Ipython not installed} -\label{sec-2} -\begin{itemize} - -\item `ERROR: matplotlib could NOT be imported! Starting normal IPython.`\\ -\label{sec-2.1}% -\end{itemize} % ends low level -\end{frame} -\begin{frame} -\frametitle{Plot UI} -\label{sec-3} -\begin{frame} - \begin{center} - \includegraphics[height=1.0in,width=4.2in]{buttons.png} - \end{center} -\end{frame} - -\frametitle{Summary} -\label{sec-4} -\begin{itemize} - -\item Start Ipython with pylab\\ -\label{sec-4.1}% -\item Using linspace\\ -\label{sec-4.2}% -\item Finding length of sequnces using len.\\ -\label{sec-4.3}% -\item Plotting mathematical functions using plot.\\ -\label{sec-4.4}% -\item Clearing drawing area using clf\\ -\label{sec-4.5}% -\item Using the UI of plot\\ -\label{sec-4.6}% -\end{itemize} % ends low level -\end{frame} - -\end{document} diff -r be96dc6c9743 -r 68813d8d80fb plotui/zoom.png Binary file plotui/zoom.png has changed diff -r be96dc6c9743 -r 68813d8d80fb progress.org --- a/progress.org Mon Nov 08 02:12:28 2010 +0530 +++ b/progress.org Thu Nov 11 02:28:55 2010 +0530 @@ -1,56 +1,56 @@ -| S.No | Name | Units | Author | Review | Checklist | -|---------+----------------------------------------+-------+----------+---------------------------------------+-----------| -| 1.2 LO: | getting started with =ipython= | 2 | Punch | Anoop(Done) | | -| 1.3 LO: | using the =plot= command interactively | 2 | Amit | Pending | | -| 1.4 LO: | embellishing a plot | 2 | Nishanth | Anoop (Done) | | -| 1.5 LO: | saving plots | 2 | Anoop | Punch (Done) | | -| 1.6 LO: | multiple plots | 3 | Madhu | Nishanth (Done) | | -| 1.7 LO: | additional features of IPython | 2 | Nishanth | Amit (Pending) | | -| 1.8 LO: | module level assessment | 3 | Madhu | | | -|---------+----------------------------------------+-------+----------+---------------------------------------+-----------| -| 2.2 LO: | loading data from files | 3 | Punch | Nishanth (Done) | | -| 2.3 LO: | plotting the data | 3 | Amit | Pending | | -| 2.4 LO: | other types of plots | 3 | Anoop | Punch (Done) | | -| 2.5 LO: | module level assessment | 3 | Nishanth | | | -|---------+----------------------------------------+-------+----------+---------------------------------------+-----------| -| 3.1 LO: | getting started with lists | 2 | Amit | Pending | | -| 3.2 LO: | getting started with =for= | 2 | Anoop | Nishanth (Done) | | -| 3.3 LO: | getting started with strings | 2 | Madhu | | | -| 3.4 LO: | getting started with files | 3 | Punch | Anoop(Done) | | -| 3.5 LO: | parsing data | 3 | Nishanth | Amit (Done) | | -| 3.6 LO: | statistics | 2 | Amit | Punch (Done) | | -| 3.7 LO: | module level assessment | 3 | Madhu | | | -|---------+----------------------------------------+-------+----------+---------------------------------------+-----------| -| 4.1 LO: | getting started with arrays | 2 | Anoop | Punch (Done) | | -| 4.2 LO: | accessing parts of arrays | 4 | Punch | Anoop (Done) | | -| 4.3 LO: | Matrices | 3 | Anoop | Punch (changes before further review) | | -| 4.4 LO: | Least square fit | 2 | Nishanth | Punch (Done) | | -| 4.5 LO: | Assessment | 3 | Punch | | | -|---------+----------------------------------------+-------+----------+---------------------------------------+-----------| -| 5.1 LO: | getting started with sage notebook | 3 | Madhu | | | -| 5.2 LO: | getting started with symbolics | 3 | Amit | Pending | | -| 5.3 LO: | using Sage | 4 | Punch | Anoop (Done) | | -| 5.4 LO: | using sage to teach | 3 | Nishanth | | | -| 5.5 LO: | Assessment | 3 | Anoop | | | -|---------+----------------------------------------+-------+----------+---------------------------------------+-----------| -| 6.1 LO: | basic datatypes & operators | 4 | Amit | Punch (Done) | | -| 6.2 LO: | I/O | 1 | Nishanth | | | -| 6.3 LO: | conditionals | 2 | Madhu | | | -| 6.4 LO: | loops | 2 | Punch | Anoop (Done) | | -| 6.5 LO: | Assessment | 3 | Anoop | | | -|---------+----------------------------------------+-------+----------+---------------------------------------+-----------| -| 7.1 LO: | manipulating lists | 3 | Madhu | | | -| 7.2 LO: | manipulating strings | 2 | Punch | Amit(Done) | | -| 7.3 LO: | getting started with tuples | 2 | Nishanth | | | -| 7.4 LO: | dictionaries | 2 | Anoop | Punch (Done) | | -| 7.5 LO: | sets | 2 | Nishanth | | | -| 7.6 LO: | Assessment | 3 | Amit | | | -|---------+----------------------------------------+-------+----------+---------------------------------------+-----------| -| 8.1 LO: | getting started with functions | 3 | Nishanth | | | -| 8.2 LO: | advanced features of functions | 3 | Punch | Anoop (Done) | | -| 8.3 LO: | using python modules | 3 | Anoop | Punch (Done) | | -| 8.4 LO: | writing python scripts | 2 | Nishanth | | | -| 8.5 LO: | testing and debugging | 2 | Amit | | | -| 8.6 LO: | Assessment | 3 | Madhu | | | -|---------+----------------------------------------+-------+----------+---------------------------------------+-----------| +| S.No | Name | Units | Author | Review | Checklist | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 1.2 LO: | getting started with =ipython= | 2 | Punch | Anoop(Done) | | +| 1.3 LO: | using the =plot= command interactively | 2 | Amit | Pending | | +| 1.4 LO: | embellishing a plot | 2 | Nishanth | Anoop (Done) | | +| 1.5 LO: | saving plots | 2 | Anoop | Punch (Done) | | +| 1.6 LO: | multiple plots | 3 | Madhu | Nishanth (Done) | | +| 1.7 LO: | additional features of IPython | 2 | Nishanth | Amit (Done) | | +| 1.8 LO: | module level assessment | 3 | Madhu | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 2.2 LO: | loading data from files | 3 | Punch | Nishanth (Done) | | +| 2.3 LO: | plotting the data | 3 | Amit | Anoop (Done) | | +| 2.4 LO: | other types of plots | 3 | Anoop | Punch (Done) | | +| 2.5 LO: | module level assessment | 3 | Nishanth | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 3.1 LO: | getting started with lists | 2 | Amit | Anoop(Done) | | +| 3.2 LO: | getting started with =for= | 2 | Anoop | Nishanth (Done) | | +| 3.3 LO: | getting started with strings | 2 | Madhu | Punch (Done) | | +| 3.4 LO: | getting started with files | 3 | Punch | Anoop(Done) | | +| 3.5 LO: | parsing data | 3 | Nishanth | Amit (Done) | | +| 3.6 LO: | statistics | 2 | Amit | Punch (Done) | | +| 3.7 LO: | module level assessment | 3 | Madhu | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 4.1 LO: | getting started with arrays | 2 | Anoop | Punch (Done) | | +| 4.2 LO: | accessing parts of arrays | 4 | Punch | Anoop (Done) | | +| 4.3 LO: | Matrices | 3 | Anoop | Punch (Done) | | +| 4.4 LO: | Least square fit | 2 | Nishanth | Punch (Done) | | +| 4.5 LO: | Assessment | 3 | Punch | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 5.1 LO: | getting started with sage notebook | 3 | Madhu | | | +| 5.2 LO: | getting started with symbolics | 3 | Amit | Pending | | +| 5.3 LO: | using Sage | 4 | Punch | Anoop (Done) | | +| 5.4 LO: | using sage to teach | 3 | Nishanth | | | +| 5.5 LO: | Assessment | 3 | Anoop | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 6.1 LO: | basic datatypes & operators | 4 | Amit | Punch (Done) | | +| 6.2 LO: | I/O | 1 | Nishanth | Amit (Done) | | +| 6.3 LO: | conditionals | 2 | Madhu | Punch (Pending) | | +| 6.4 LO: | loops | 2 | Punch | Anoop (Done) | | +| 6.5 LO: | Assessment | 3 | Anoop | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 7.1 LO: | manipulating lists | 3 | Madhu | Punch (Done) | | +| 7.2 LO: | manipulating strings | 2 | Punch | Amit (Done) | | +| 7.3 LO: | getting started with tuples | 2 | Nishanth | Punch (Done) | | +| 7.4 LO: | dictionaries | 2 | Anoop | Punch (Done) | | +| 7.5 LO: | sets | 2 | Nishanth | Punch (Done) | | +| 7.6 LO: | Assessment | 3 | Amit | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 8.1 LO: | getting started with functions | 3 | Anoop | Pending | | +| 8.2 LO: | advanced features of functions | 3 | Punch | Anoop (Done) | | +| 8.3 LO: | using python modules | 3 | Anoop | Punch (Done) | | +| 8.4 LO: | writing python scripts | 2 | Nishanth | | | +| 8.5 LO: | testing and debugging | 2 | Amit | | | +| 8.6 LO: | Assessment | 3 | Madhu | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| diff -r be96dc6c9743 -r 68813d8d80fb savefig/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/savefig/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,5 @@ +Saving a plot(png):\\ +{\ex \lstinline| savefig('filename.png')|} + +Saving a plot(pdf):\\ +{\ex \lstinline| savefig('filename.pdf')|} diff -r be96dc6c9743 -r 68813d8d80fb sets/script.rst --- a/sets/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/sets/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -22,15 +22,15 @@ Script ------ -Hello friends and welcome to the tutorial on Sets +{{{ Show the slide containing title }}} -{{{ Show the slide containing title }}} +Hello friends and welcome to the tutorial on Sets {{{ Show the slide containing the outline slide }}} In this tutorial, we shall learn - * sets + * sets * operations on sets Sets are data structures which contain unique elements. In other words, @@ -40,7 +40,7 @@ type :: - a_list = [1, 2, 1, 4, 5, 6, 7] + a_list = [1, 2, 1, 4, 5, 6, 2] a = set(a_list) a @@ -55,7 +55,7 @@ p10 is the set of prime numbers from 1 to 10. Various operations that we do on sets are possible here also. -The | character stands for union +The | (pipe) character stands for union :: f10 | p10 @@ -89,19 +89,19 @@ b = set([1, 2]) b < f10 -gives a True since b is a proper subset of f10. +gives a ``True`` since b is a proper subset of f10. Similarly, :: f10 < f10 -gives a False since f10 is not a proper subset. +gives a ``False`` since f10 is not a proper subset. hence the right way to do would be :: f10 <= f10 -and we get a True since every set is a subset of itself. +and we get a ``True`` since every set is a subset of itself. Sets can be iterated upon just like lists and tuples. :: @@ -122,7 +122,7 @@ 1 in f10 2 in f10 -prints True and False respectively +prints ``True`` and ``False`` respectively The order in which elements are organised in a set is not to be relied upon since sets do not support indexing. Hence, slicing and striding are not valid @@ -161,7 +161,6 @@ {{{ Show the "sponsored by FOSSEE" slide }}} -#[Nishanth]: Will add this line after all of us fix on one. This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India Hope you have enjoyed and found it useful. diff -r be96dc6c9743 -r 68813d8d80fb sets/slides.org --- a/sets/slides.org Mon Nov 08 02:12:28 2010 +0530 +++ b/sets/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -43,8 +43,10 @@ for mark in marks_set: marks.remove(mark) - # we are now left with only duplicates in the list marks + # we are now left with only duplicates + # in the list marks duplicates = set(marks) + #+end_src * Summary You should now be able to -- diff -r be96dc6c9743 -r 68813d8d80fb sets/slides.tex --- a/sets/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/sets/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,4 +1,4 @@ -% Created 2010-10-10 Sun 23:53 +% Created 2010-11-09 Tue 17:14 \documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} \usepackage[T1]{fontenc} @@ -67,7 +67,8 @@ for mark in marks_set: marks.remove(mark) -# we are now left with only duplicates in the list marks +# we are now left with only duplicates +# in the list marks duplicates = set(marks) \end{lstlisting} \end{frame} diff -r be96dc6c9743 -r 68813d8d80fb statistics/football.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/statistics/football.txt Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,8 @@ +Cristiano Ronaldo, 86 ,67 +latan Ibrahimovic, 34 , 65 +Lionel Messi , 45 , 41 +Samuel Eto’o , 23 , 24 +Kaka , 43 , 45 +Frank Lampard , 65 ,34 + + diff -r be96dc6c9743 -r 68813d8d80fb statistics/script.rst --- a/statistics/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/statistics/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -13,9 +13,11 @@ .. Getting started with IPython .. Loading Data from files .. Getting started with Lists +.. Accessing Pieces of Arrays + -.. Author : Puneeth - Internal Reviewer : Anoop Jacob Thomas +.. Author : Amit Sethi + Internal Reviewer : Puneeth External Reviewer : Checklist OK? : [2010-10-05] @@ -28,17 +30,13 @@ {{{ Show the slide containing the outline slide }}} In this tutorial, we shall learn - * Doing simple statistical operations in Python - * Applying these to real world problems - -.. #[punch: the prerequisites part may be skipped in the tutorial. It -.. will be provided separately.] + * Doing statistical operations in Python + * Summing set of numbers + * Finding there mean + * Finding there Median + * Finding there Standard Deviation + -You will need Ipython with pylab running on your computer to use this -tutorial. - -Also you will need to know about loading data using loadtxt to be able -to follow the real world application. .. #[punch: since loadtxt is anyway a pre-req, I would recommend you .. to use a data file and load data from that. that is good, since you @@ -53,88 +51,13 @@ .. smaller data-set or something. Using lists doesn't seem natural.] -We will first start with the most necessary statistical operation i.e -finding mean. - -We have a list of ages of a random group of people :: - - age_list = [4,45,23,34,34,38,65,42,32,7] - -One way of getting the mean could be getting sum of all the ages and -dividing by the number of people in the group. :: - - sum_age_list = sum(age_list) - -sum function gives us the sum of the elements. Note that the -``sum_age_list`` variable is an integer and the number of people or -length of the list is also an integer. We will need to convert one of -them to a float before carrying out the division. :: - - mean_using_sum = float(sum_age_list)/len(age_list) - -This obviously gives the mean age but there is a simpler way to do -this in Python - using the mean function:: - - mean(age_list) - -Mean can be used in more ways in case of 2 dimensional lists. Take a -two dimensional list :: - - two_dimension=[[1,5,6,8],[1,3,4,5]] - -The mean function by default gives the mean of the flattened sequence. -A Flattened sequence means a list obtained by concatenating all the -smaller lists into a large long list. In this case, the list obtained -by writing the two lists one after the other. :: - - mean(two_dimension) - flattened_seq=[1,5,6,8,1,3,4,5] - mean(flattened_seq) - -As you can see both the results are same. ``mean`` function can also -give us the mean of each column, or the mean of corresponding elements -in the smaller lists. :: - - mean(two_dimension, 0) - array([ 1. , 4. , 5. , 6.5]) - -we pass an extra argument 0 in that case. - -If we use an argument 1, we obtain the mean along the rows. :: - - mean(two_dimension, 1) - array([ 5. , 3.25]) - -We can see more option of mean using :: - - mean? - -Similarly we can calculate median and stanard deviation of a list -using the functions median and std:: - - median(age_list) - std(age_list) - -Median and std can also be calculated for two dimensional arrays along -columns and rows just like mean. - -For example :: - - median(two_dimension, 0) - std(two_dimension, 1) - -This gives us the median along the colums and standard devition along -the rows. - -Now lets apply this to a real world example - -We will a data file that is at the a path ``/home/fossee/sslc2.txt``. -It contains record of students and their performance in one of the -State Secondary Board Examination. It has 180, 000 lines of record. We -are going to read it and process this data. We can see the content of -file by double clicking on it. It might take some time to open since -it is quite a large file. Please don't edit the data. This file has -a particular structure. +For this tutorial We will use data file that is at the a path +``/home/fossee/sslc2.txt``. It contains record of students and their +performance in one of the State Secondary Board Examination. It has +180,000 lines of record. We are going to read it and process this +data. We can see the content of file by double clicking on it. It +might take some time to open since it is quite a large file. Please +don't edit the data. This file has a particular structure. We can do :: @@ -142,6 +65,9 @@ to check the contents of the file. + +{{{ Show the data structure on a slide }}} + Each line in the file is a set of 11 fields separated by semi-colons Consider a sample line from this file. A;015163;JOSEPH RAJ S;083;042;47;00;72;244;;; @@ -155,45 +81,97 @@ * Total marks 244 -Now lets try and find the mean of English marks of all students. - -For this we do. :: +Lets try and load this data as an array and then run various function on +it. - L=loadtxt('/home/fossee/sslc2.txt',usecols=(3,),delimiter=';') +To get the data as an array we do. :: + + L=loadtxt('/home/amit/sslc2.txt',usecols=(3,4,5,6,7,),delimiter=';') L - mean(L) + loadtxt function loads data from an external file.Delimiter specifies -the kind of character are the fields of data seperated by. -usecols specifies the columns to be used so (3,). The 'comma' is added -because usecols is a sequence. +the kind of character are the fields of data seperated by. usecols +specifies the columns to be used so (3,4,5,6,7) loads those +colums. The 'comma' is added because usecols is a sequence. -To get the median marks. :: +As we can see L is an array. We can get the shape of this array using:: - median(L) + L.shape + (185667, 5) + +Lets start applying statistics operations on these. We will start with +the most basic, summing. How do you find the sum of marks of all +subjects for the first student. + +As we know from our knowledge of accessing pieces of arrays. To acess +the first row we will do :: -Standard deviation. :: - - std(L) + L[0,:] + +Now to sum this we can say :: + totalmarks=sum(L[0,:]) + totalmarks -Now lets try and and get the mean for all the subjects :: +To get the mean we can do :: + + totalmarks/len(L[0,:]) + +or simply :: + + mean(L[0,:]) - L=loadtxt('/home/fossee/sslc2.txt',usecols=(3,4,5,6,7),delimiter=';') - mean(L,0) - array([ 73.55452504, 53.79828941, 62.83342759, 50.69806158, 63.17056881]) +But we have such a large data set calculating one by one the mean of +each student is impossible. Is there a way to reduce the work. + +For this we will look into the documentation of mean by doing:: -As we can see from the result mean(L,0). The resultant sequence -is the mean marks of all students that gave the exam for the five subjects. + mean? -and :: - +As we know L is a two dimensional array. We can calculate the mean +across each of the axis of the array. The axis of rows is referred by +number 0 and columns by 1. So to calculate mean accross all colums we +will pass extra parameter 1 for the axis.:: + mean(L,1) - -is the average accumalative marks of individual students. Clearly, mean(L,0) -was a row wise calcultaion while mean(L,1) was a column wise calculation. +L here is the two dimensional array. + +Similarly to calculate average marks scored by all the students for each +subject can be calculated using :: + + mean(L,0) + +Next lets now calculate the median of English marks for the all the students +We can access English marks of all students using :: + + L[:,0] + +To get the median we will do :: + + median(L[:,0]) +For all the subjects we can use the same syntax as mean and calculate +median across all rows using :: + + median(L,0) + + +Similarly to calculate standard deviation for English we can do:: + + std(L[:,0]) + +and for all rows:: + + std(L,0) + +Following is an exercise that you must do. + +%% %% In the given file football.txt at path /home/fossee/football.txt , one column is player name,second is goals at home and third goals away. + 1.Find the total goals for each player + 2.Mean home and away goals + 3.Standard deviation of home and away goals {{{ Show summary slide }}} diff -r be96dc6c9743 -r 68813d8d80fb statistics/slides.org --- a/statistics/slides.org Mon Nov 08 02:12:28 2010 +0530 +++ b/statistics/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -2,32 +2,73 @@ #+LaTeX_CLASS_OPTIONS: [presentation] #+BEAMER_FRAME_LEVEL: 1 -#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} #+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) #+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC -#+OPTIONS: H:5 num:t toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} #+TITLE: Statistics #+AUTHOR: FOSSEE -#+DATE: 2010-09-14 Tue +#+DATE #+EMAIL: info@fossee.in -# \author[FOSSEE] {FOSSEE} +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + + +* Outline + - Doing statistical operations in Python + - Summing set of numbers + - Finding there mean + - Finding there Median + - Finding there Standard Deviation + +* Data set + - A;015163;JOSEPH RAJ S;083;042;47;00;72;244;;; -# \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -# \date{} + The following are the fields in any given line. + - Region Code which is 'A' + - Roll Number 015163 + - Name JOSEPH RAJ S + - Marks of 5 subjects: -- English 083 -- + Hindi 042 -- Maths 47 -- + Science 35 -- Social 72 + - Total marks 244 -* Tutorial Plan -** Doing simple statistical operations in Python -** Using loadtxt to solve statistics problem +* Question + - In the given file football.txt at path /home/fossee/football.txt , + one column is player name,second is goals at home + and third goals away. + - Find the total goals for each player + - Mean home and away goals + - Standard deviation of home and away goals + +* Solution +#+begin_src python + L=loadtxt('/home/amit/football.txt',usecols=(1,2), + delimiter=',') + sum(L,1) + mean(L,0) + std(L,0) +#+end_src python * Summary -** seq=[1,5,6,8,1,3,4,5] -** sum(seq) -** mean(seq) -** median(seq) -** std(seq) + - sum + - mean + - median + - std -* Summary - -** loadtxt diff -r be96dc6c9743 -r 68813d8d80fb statistics/slides.tex --- a/statistics/slides.tex Mon Nov 08 02:12:28 2010 +0530 +++ b/statistics/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -1,106 +1,122 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\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} +% Created 2010-11-11 Thu 01:35 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} - -\definecolor{darkgreen}{rgb}{0,0.5,0} - +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} \usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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}} +\title{Statistics} +\author{FOSSEE} +\date{11 November 2010} -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} -\date{} - -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} -\begin{frame} - \maketitle -\end{frame} +\maketitle -\begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} -\end{frame} + + -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + -\begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} -\end{frame} + + \begin{frame} - \frametitle{Thank you!} - \begin{block}{} - \begin{center} - This spoken tutorial has been produced by the - \textcolor{blue}{FOSSEE} team, which is funded by the - \end{center} - \begin{center} - \textcolor{blue}{National Mission on Education through \\ - Information \& Communication Technology \\ - MHRD, Govt. of India}. - \end{center} - \end{block} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Doing statistical operations in Python + +\begin{itemize} +\item Summing set of numbers +\item Finding there mean +\item Finding there Median +\item Finding there Standard Deviation +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Data set} +\label{sec-2} + +\begin{itemize} +\item A;015163;JOSEPH RAJ S;083;042;47;00;72;244;;; +\end{itemize} + + + The following are the fields in any given line. +\begin{itemize} +\item Region Code which is `A' +\item Roll Number 015163 +\item Name JOSEPH RAJ S +\item Marks of 5 subjects: -- English 083 -- + Hindi 042 -- Maths 47 -- + Science 35 -- Social 72 +\item Total marks 244 +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question} +\label{sec-3} + +\begin{itemize} +\item In the given file football.txt at path /home/fossee/football.txt , + one column is player name,second is goals at home + and third goals away. + +\begin{itemize} +\item Find the total goals for each player +\item Mean home and away goals +\item Standard deviation of home and away goals +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution} +\label{sec-4} + +\begin{verbatim} +L=loadtxt('/home/amit/football.txt',usecols=(1,2), + delimiter=',') +sum(L,1) +mean(L,0) +std(L,0) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-5} + +\begin{itemize} +\item sum +\item mean +\item median +\item std +\end{itemize} \end{frame} \end{document} diff -r be96dc6c9743 -r 68813d8d80fb testing-debugging/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/testing-debugging/questions.rst Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,28 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Question 1 + + Answer: Answer 1 + + OR + + Answer:: + + answer code line 1 + answer code line 2 + answer code line 3 + +2. Question 2 +3. Question 3 + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Question 1 +2. Question 2 diff -r be96dc6c9743 -r 68813d8d80fb testing-debugging/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/testing-debugging/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,8 @@ +Creating a linear array:\\ +{\ex \lstinline| x = linspace(0, 2*pi, 50)|} + +Plotting two variables:\\ +{\ex \lstinline| plot(x, sin(x))|} + +Plotting two lists of equal length x, y:\\ +{\ex \lstinline| plot(x, y)|} diff -r be96dc6c9743 -r 68813d8d80fb testing-debugging/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/testing-debugging/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,313 @@ +.. Objectives +.. ---------- + +.. Writing Simple Tests (Applying) +.. Automating these tests +.. Coding Style +.. Errors and Exceptions + +.. Prerequisites +.. ------------- + +.. 1. Getting started with functions +.. 2. Advanced Features of Functions + +.. Author : Amit Sethi + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +{{{ Show the slide containing title }}} + +Hello Friends. Welcome to this tutorial on Testing and Debugging. + +{{{ Show the outline slide }}} + +In this tutorial we will learn. + +1.What software Testing is? +2.Learn to test simple functions for their functionality. +3.Learn how to automate tests. +4.Need for coding style and some of the standards followed by the Python Community. +5.Handling Errors and Exceptions. + +Software testing is an activity aimed at evaluating a program +and determining that it meets its required results. + +{{{ Slide with the function }}} + +Lets first write a simple function to calculate gcd of two numbers.:: + + def gcd(a, b): + if b == 0: + return a + return gcd(b, a%b) + +save this into a file "/home/fossee/gcd.py". + +Now we need to evaluate this function. Thus we have to check whether +function successfully gives us the gcd of two whole numbers. Thus we need +a set of inputs and the exact outputs that are expected for those input +test cases. + +Let our test case be 48 and 64 as *a* and *b* respectively. For this test +case we know that the GCD is 16. So that is the expected output. + +{{{ Slide with change in code }}} + +Let us include code for testing in our **gcd.py** file :: + + def gcd(a, b): + if b == 0: + return a + return gcd(b, a%b) + + if __name__ == '__main__': + result = gcd(48, 64) + if result != 16: + print "Test failed for the case a=48 and b=64. Expected 16. Obtained %d instead." % result + print "Test Passed" + +Note that we have introduced a new semantic which uses two new magic names +in Python *__name__* and *__main__*. This is a very common idiom used in +Python. Every Python code in a file can be run in two ways: Either as an +independent stand-alone script or as a Python module which can be imported +by other Python scripts or modules. When the idiom:: + + if __name__ == '__main__': + +{{{ Slide with the idiom }}} + + +is used, the code within this if block is executed first when we run the +Python file as a stand-alone script. In other words, when we run this +python file as a stand-alone script the control of the program first starts +from the code that is within this if block from which the control is +transferred to other parts of the program or to other modules from +here. This comes as an extremely handy feature especially when we want to +test our modules individually. + +But there can be a number of places where the gcd function might break would we +have to right a seperate test case for all of them. + +Following is an (are) exercise(s) that you must do. + +%% %% Write code for lcm and write tests for it + +%% %% Answer is on the screen. + +Well thats where automating tests come in. We can run many tests to check where our +code can break. Lets see this with an example. Lets try and automate tests on the +gcd function. For this we will write a file with test cases and call the function +for all of them. + +{{{ Slide with the structure of file }}} + +The structure of the file will be the two parameters and the output result seperated +by space:: + + | 12 | 28 | 4 | + | 18 | 36 | 18 | + | 4678 | 39763 | 2339 | + +The file structure is shown in form a table here. + + +{{{ Slide with code piece }}} + +We add the code piece to automate the test.:: + + + if __name__ == '__main__': + for line in open('testcases.txt'): + numbers = line.split() + x = int(numbers[0]) + y = int(numbers[1]) + result = int(numbers[2]) + if gcd(x, y) != result: + print "Failed gcd test for", x, y + +%% %% Pause the video do the following exercise +%% %% For the same inputs as gcd write automated tests for LCM. +%% %% The solution is on the screen + +For any program there can be innumerable test cases thus it is not +possible to test cases. However there are many ideas to reduce the set of +test cases by testing those cases that are more likely to show errors. + +Moving from testing lets talk a bit about coding style now. + +Apart from from being able to perform the required task, a property +of a good program is its readability. Code is read more often than it is +written. This is because that way other people can learn from it and extend +and improve it. There are certain pointers for readable code that I am going to discuss. + +First, Naming variables. + +{{{ Slide with code snippet }}} + +Choose name that by which people will most likely guess the usage.Lets look at this +with an example:: + + amount = 12.68 + denom = 0.05 + nCoins = round(amount/denom) + rAmount = nCoins * denom + +As we can see in the example it is very easy to make what the code is doing. + +One can almost read it as English sentences. +Amount is 12.68 +Denomination is .05 +Number of coins is round of amount by denominations. + +Proper naming helps so much in understanding the code. + +{{{ Slide with code style points }}} + +Also one should use. :: + + 1.Four Space Indentation + 2.Limit to 79 characters a line, but readability should come first. + 3.Functions and methods should be separated with two blank lines. + Class definitions with three blank lines. + 4.No inline comments, comments should be above the line they comment. + 5.Use Docstring to explain units of code performing specific task like + functions. + 6.We should always have whitespace around operators and after punctuation. + +%% %% Pause and do the following exercise +%% %% Give meaningful names to the variables in the gcd code . + + + +This will help enormously towards making our program more readable. + +From coding style lets move on to handling errors and exceptions. + +{{{ Slide with code snippet }}} + +Lets try out the following piece of code:: + + while True print 'Hello world' + +{{{ Slide with Error }}} + +what happens when we do this on the interpreter. The interpreter +says that this is a syntax error. Syntax error are caused when we +do not follow the rules of the programming language. + +{{{ Slide with expression }}} + +However lets try an expression like :: + + 1/0 + +{{{ Slide with Error }}} + +Although this expression follows the programming language rules, +however it is not possible to express the solution of this expression. +Thus python throws an exception called ZeroDivisionError. Exception +is special kind of failure reported by the programming language. + + + +Lets see why and how we can use Exception in our programs. + +{{{ Slide with code snippet }}} + +Type on your interpreter:: + + a = raw_input("Enter a number:") + num = int(a) + +{{{ Run this code on interpreter with a character input }}} + +You will notice that when you run this program and give and +non-numeric input it throws a 'ValueError' Exception. + +So now we can 'catch' this exception and write code to +handle it. + +{{{ Slide with code snippet }}} + +For this we have try and except clause in python. Lets change our +previous code slightly.:: + + a = raw_input("Enter a number") + try: + num = int(a) + except: + print "Wrong input ..." + +{{{ Run the code with character input }}} + +In this piece of code python tries to run the code inside the try +block but when if it fails it executes the code block in except. + +In previous example we encountered a problem with running our conversion +to integer code. We found out what caused the error and then deviced a solution +for it this whole process is called debugging. + +One can understand the debugging process using the figure. + +In debugging process we form a hypothesis of what causes the error. +Test if it is correct by changing the code. And refine the hypothesis +on the basis of our result. + +{{{ Slide with code snippet }}} + +Lets see another example of debugging. Create a file mymodule.py and +add the following code:: + + def test(): + total=1+1 + print spam + +{{{ Slide with code snippet }}} + +Lets now try and run this code :: + + import mymodule + mymodule.test() + +Interpreter gives us an error because spam is not defined +but lets now do %debug on ipython interpreter. The prompt on the shell has changed to ipdb. This is debugger here you can access variables in that code block for example 'total'unlike the normal interpreter. + +%% %% Pause and do the following exercise +%% %% Do the gcd program which takes input from user which tells +%% %% the user wrong input if it is not valid and quits for 'q'. + + + +This brings us to the end of this tutorial on testing and debugging. + + + + +{{{ Show the summary slide }}} + +In this tutorial we have learned to +1.Create simple tests for a function. +2.Learn to Automate tests using many predefined test cases. +3.Good coding standards. +4.Difference between syntax error and exception. +5.Handling exception using try and except. +6.Using %debug for debugging on ipython. + +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you! + + + + + + + diff -r be96dc6c9743 -r 68813d8d80fb testing-debugging/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/testing-debugging/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,86 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{red}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Testing and debugging +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - What software Testing is? + - Learn to test simple functions for their functionality. + - Learn how to automate tests. + - Need for coding style and some of the standards followed by the Python Community. + - Handling Errors and Exceptions. + + +* gcd function + - Create gcd.py file with: +#+begin_LaTeX +\begin{lstlisting}[language=python] + def gcd(a, b): + if a % b == 0: + return b + return gcd(b, a%b) +\end{lstlisting} +#+end_LaTeX + +* Test for gcd.py + - Edit gcd.py file +#+begin_LaTeX +\begin{lstlisting}[language=python] + + def gcd(a, b): + if b == 0: + return a + return gcd(b, a%b) + + if __name__=='__main__': + result = gcd(48, 64) + if result != 16: + print "Test failed" + print "Test Passed" +\end{lstlisting} +#+end_LaTeX + +* Automating tests +#+begin_LaTeX +\begin{lstlisting}[language=python] + + if __name=__='__main__': + for line in open('numbers.txt'): + numbers = line.split() + x = int(numbers[0]) + y = int(numbers[1]) + result = int(numbers[2]) + if gcd(x, y) != result: + print "Failed gcd test + for", x, y +\end{lstlisting} +#+end_LaTeX + + + diff -r be96dc6c9743 -r 68813d8d80fb testing-debugging/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/testing-debugging/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,120 @@ +% Created 2010-11-07 Sun 18:57 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{red}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Testing and debugging} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item What software Testing is? +\item Learn to test simple functions for their functionality. +\item Learn how to automate tests. +\item Need for coding style and some of the standards followed by the Python Community. +\item Handling Errors and Exceptions. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{gcd function} +\label{sec-2} + +\begin{itemize} +\item Create gcd.py file with: +\end{itemize} + +\begin{lstlisting}[language=python] + def gcd(a, b): + if a % b == 0: + return b + return gcd(b, a%b) +\end{lstlisting} +\end{frame} +\begin{frame}[fragile] +\frametitle{Test for gcd.py} +\label{sec-3} + +\begin{itemize} +\item Edit gcd.py file +\end{itemize} + +\begin{lstlisting}[language=python] + + def gcd(a, b): + if b == 0: + return a + return gcd(b, a%b) + + if __name__=='__main__': + result = gcd(48, 64) + if result != 16: + print "Test failed" + print "Test Passed" +\end{lstlisting} +\end{frame} +\begin{frame}[fragile] +\frametitle{Automating tests} +\label{sec-4} + +\begin{lstlisting}[language=python] + + if __name=__='__main__': + for line in open('numbers.txt'): + numbers = line.split() + x = int(numbers[1]) + y = int(numbers[2]) + result = int(numbers[3]) + if gcd(x, y) != result: + print "Failed gcd test + for", x, y +\end{lstlisting} + + + + +$^{1}$ FOOTNOTE DEFINITION NOT FOUND: 0 + +$^{2}$ FOOTNOTE DEFINITION NOT FOUND: 1 + +$^{3}$ FOOTNOTE DEFINITION NOT FOUND: 2 +\end{frame} + +\end{document} diff -r be96dc6c9743 -r 68813d8d80fb tuples/questions.rst --- a/tuples/questions.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/tuples/questions.rst Thu Nov 11 02:28:55 2010 +0530 @@ -58,3 +58,10 @@ Answer: (6, 5, 4, 3, 2, 1) + 10. What is the output of the code block below:: + + a = "hello", "bye", "welcome", "goodnight" + type(a) + + Answer: + diff -r be96dc6c9743 -r 68813d8d80fb tuples/script.rst --- a/tuples/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/tuples/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -1,15 +1,10 @@ .. Objectives .. ---------- -.. A - Students and teachers from Science and engineering backgrounds - B - Will learn what are tuples and why they are needed - Will learn the various methods of accessing elements in tuples - C - - D - - -.. #. what are tuples -.. #. comparison with lists -.. #. why are they needed +.. At the end of the tutorial, you will +.. #. have a clear understand of what tuples are +.. #. be able to compare them with lists +.. #. know why they are needed and where to use them .. Prerequisites @@ -25,7 +20,8 @@ Script ------ -Hello friends and welcome to the tutorial on Tuples +Hello friends and welcome to the tutorial on getting started with +tuples. {{{ Show the slide containing title }}} @@ -37,9 +33,10 @@ * their similarities and dissimilarities with lists * why are they needed -Let`s get started by defining a tuple. A tuple is defined by enclosing -parantheses around a sequence of items seperated by commas. It is similar to -defining a list except that parantheses are used instead of square brackets. +Let's get started by defining a tuple. A tuple is defined by enclosing +parentheses around a sequence of items seperated by commas. It is +similar to defining a list except that parentheses are used instead of +square brackets. :: t = (1, 2.5, "hello", -4, "world", 1.24, 5) @@ -66,10 +63,10 @@ t[2] = "Hello" We can see that, it raises an error saying tuple does not support item -assignment. It only implies that tuples are immutable or in simple words, -tuples cannot be changed. +assignment. Tuples are immutable, and cannot be changed after +creation. -But what is the use of tuples!!! +Then, what's the use of tuples? We shall understand that soon. But let us look at a simple problem of swapping values. @@ -110,8 +107,9 @@ a b -We see that the values are swapped. -This idiom works for different datatypes also. +We see that the values are swapped. This idiom works for different +data-types also. + :: a = 2.5 @@ -120,8 +118,8 @@ a b -Moreover this type of behaviour is straight forward and what you would expect -should happen naturally. +Moreover this type of behaviour is something that feels natural and +you'd expect to happen. This is possible because of the immutability of tuples. This process is called tuple packing and unpacking. @@ -136,10 +134,10 @@ 5, "hello", 2.5 -Now it is a tuple with two elements. +Now it is a tuple with three elements. So when we are actually typing two or more elements seperated by commas, those -elements are packed and a tuple is made from them. +elements are packed into a tuple. When you type :: @@ -165,9 +163,8 @@ {{{ Show the "sponsored by FOSSEE" slide }}} -#[Nishanth]: Will add this line after all of us fix on one. This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India Hope you have enjoyed and found it useful. -Thankyou +Thank you diff -r be96dc6c9743 -r 68813d8d80fb using python modules/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,16 @@ +Import all definitions to current name-space:\\ +{\ex \lstinline| from scipy import *|} + +Import few definitions to current name-space:\\ +{\ex \lstinline| from scipy import linspace, pi, sin|} + +Import a module as a new name-space:\\ +{\ex \lstinline| import scipy|} + +Few standard python modules:\\ +{\ex \lstinline| Math: math, random|} +{\ex \lstinline| Internet: urllib2, smtplib|} +{\ex \lstinline| System: sys|} +{\ex \lstinline| OS: os|} +{\ex \lstinline| Regular Expression: re|} +{\ex \lstinline| Compression: gzip, zipfile, tarfile|} diff -r be96dc6c9743 -r 68813d8d80fb using python modules/script.rst --- a/using python modules/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/using python modules/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -28,15 +28,13 @@ ==================== {{{ show the welcome slide }}} -Welcome to the spoken tutorial on using python modules. +Welcome to the spoken tutorial on Using Python Modules. {{{ switch to next slide, outline slide }}} In this tutorial, we will see how to run python scripts from command -line. See importing modules, importing scipy and pylab modules. And -also see the Python standard library. - -.. #[Punch: the sentence seems discontinuous.] +line. We'll see how to import modules, importing scipy and pylab +modules and have a look at the Python standard library. {{{ switch to next slide on executing python scripts from command line }}} @@ -49,7 +47,7 @@ print "Hello world!" print -and save the script as hello.py, +and save the script as ``hello.py``, {{{ save the script as hello.py }}} @@ -187,7 +185,7 @@ {{{ switch to next slide, problem statement }}} -Write a script to plot a sine wave from minus two pi to two pi. +%% %% Write a script to plot a sine wave from minus two pi to two pi. Pause here and try to solve the problem yourself before looking at the solution. @@ -234,8 +232,8 @@ Find more information at Python Library reference, ``http://docs.python.org/library/`` -The modules pylab, scipy, Mayavi are not part of the standard python -library. +There are a lot of other modules like pylab, scipy, Mayavi, etc which +are not part of the standard python library. {{{ switch to next slide, summary }}} diff -r be96dc6c9743 -r 68813d8d80fb using-plot-interactively/buttons.png Binary file using-plot-interactively/buttons.png has changed diff -r be96dc6c9743 -r 68813d8d80fb using-plot-interactively/home.png Binary file using-plot-interactively/home.png has changed diff -r be96dc6c9743 -r 68813d8d80fb using-plot-interactively/move.png Binary file using-plot-interactively/move.png has changed diff -r be96dc6c9743 -r 68813d8d80fb using-plot-interactively/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using-plot-interactively/questions.rst Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,51 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Create 100 equally spaced points between -pi/2 and pi/2? + + Answer: linspace(-pi/2,pi/2,100) + +2. How do you clear a figure in ipython? + + Answer: clf() + +3. How do find the length of a sequence? + + Answer: len(sequence_name) + +4. Create a plot of x and e^x where x is 100 equally spaced points between 0,pi. Hint: e^x -> exp(x) for ipython + + Answer: x=linspace(0,pi,100) + plot(x,exp(x)) + +5. List four formats in which you can save a plot in ipython? + + Answer: png,eps,pdf,ps + +6. List the kind of buttons available in plotui to study the plot better ? + + Zoom button to Zoom In to a region. + Pan button to move it around. + +7. What are the left and right arrow buttons for? + + Answer: These buttons take you to the states that the plot has been. Much like a browser left and right arrow button. + + + +8. What is the home button for in the Plot UI? + + Initial State of the plot. + + + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Use '?' and explain the similarities and difference between linpace and logspace? +2. Describe one by one all the buttons in UI of plot and their meaning? diff -r be96dc6c9743 -r 68813d8d80fb using-plot-interactively/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using-plot-interactively/quickref.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,14 @@ +Creating a linear array:\\ +{\ex \lstinline| x = linspace(0, 2*pi, 50)|} + +Plotting two variables:\\ +{\ex \lstinline| plot(x, sin(x))|} + +Saving Plot\\ +{\includegraphics[width=60mm]{save.png}} + +Zooming into a part of the plot\\ +{\includegraphics[width=60mm]{zoom.png}} + +Move the plot\\ +{\includegraphics[width=60mm]{move.png}} diff -r be96dc6c9743 -r 68813d8d80fb using-plot-interactively/save.png Binary file using-plot-interactively/save.png has changed diff -r be96dc6c9743 -r 68813d8d80fb using-plot-interactively/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using-plot-interactively/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,212 @@ +.. Objectives +.. ---------- + +.. By the end of this tutorial you will -- + +.. 1. Create simple plots of mathematical functions +.. #. Use the Figure window to study plots better + + + +.. Prerequisites +.. ------------- + +.. Installation of required tools +.. Ipython + +.. Author : Amit Sethi + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------- + + +Hello and welcome to the tutorial on creating simple plots using +Python.This tutorial is presented by the Fossee group. +{{{ Show the Title Slide }}} + +I hope you have IPython running on your computer. + +In this tutorial we will look at plot command and also how to study +the plot using the UI. + +{{{ Show Outline Slide }}} + +Lets start ipython on your shell, type :: + + $ipython -pylab + + +Pylab is a python library which provides plotting functionality.It +also provides many other important mathematical and scientific +functions. After running IPython -pylab in your shell if at the top of +the result of this command, you see something like :: + + + `ERROR: matplotlib could NOT be imported! Starting normal + IPython.` + + +{{{ Slide with Error written on it }}} + + + + +Then you have to install matplotlib and run this command again. + +Now type in your ipython shell :: + + In[]: linpace? + + + +as the documentation says, it returns `num` evenly spaced samples, +calculated over the interval start and stop. To illustrate this, lets +do it form 1 to 100 and try 100 points. :: + + In[]: linspace(1,100,100) + +As you can see a sequence of numbers from 1 to 100 appears. + +Now lets try 200 points between 0 and 1 you do this by typing :: + + + In[]: linspace(0,1,200) + +0 for start , 1 for stop and 200 for no of points. In linspace +the start and stop points can be integers, decimals , or +constants. Let's try and get 100 points between -pi to pi. Type :: + + In[]: p = linspace(-pi,pi,100) + + +'pi' here is constant defined by pylab. Save this to the variable, p +. + +If you now :: + + In[]: len(p) + +You will get the no. of points. len function gives the no of elements +of a sequence. + + +Let's try and plot a cosine curve between -pi and pi using these +points. Simply type :: + + + In[]: plot(p,cos(points)) + +Here cos(points) gets the cosine value at every corresponding point to +p. + + +We can also save cos(points) to variable cosine and plot it using +plot.:: + + In[]: cosine=cos(points) + + In[]: plot(p,cosine) + + + +Now do :: + + In[]: clf() + +this will clear the plot. + +This is done because any other plot we try to make shall come on the +same drawing area. As we do not wish to clutter the area with +overlaid plots , we just clear it with clf(). Now lets try a sine +plot. :: + + + In []: plot(p,sin(p)) + + + + +The Window on which the plot appears can be used to study it better. + +{{{ Show the slide with all the buttons on it }}} + +First of all moving the mouse around gives us the point where mouse +points at. + +Also we have some buttons the right most among them is +for saving the file. + +Just click on it specifying the name of the file. We will save the plot +by the name sin_curve in pdf format. + + + +{{{ Action corelating with the words }}} + +As you can see I can specify format of file from the dropdown. + +Formats like png ,eps ,pdf, ps are available. + +Left to the save button is the slider button to specify the margins. + +{{{ Action corelating with the words }}} + +Left to this is zoom button to zoom into the plot. Just specify the +region to zoom into. +The button left to it can be used to move the axes of the plot. + +{{{ Action corelating with the words }}} + +The next two buttons with a left and right arrow icons change the state of the +plot and take it to the previous state it was in. It more or less acts like a +back and forward button in the browser. + +{{{ Action corelating with the words }}} + +The last one is 'home' referring to the initial plot. + +{{{ Action corelating with the words}}} + + + +{{{ Summary Slide }}} + + +In this tutorial we have looked at + +1. Starting Ipython with pylab + +2. Using linspace function to create `num` equaly spaced points in a region. + +3. Finding length of sequnces using len. + +4. Plotting mathematical functions using plot. + +4. Clearing drawing area using clf + +5. Using the UI of plot for studying it better . Using functionalities like save , zoom and moving the plots on x and y axis + + + + + +{{{ Show the "sponsored by FOSSEE" slide }}} + + + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + + + + Hope you have enjoyed and found it useful. + + Thankyou + + + +Author : Amit Sethi +Internal Reviewer : +Internal Reviewer 2 : diff -r be96dc6c9743 -r 68813d8d80fb using-plot-interactively/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using-plot-interactively/slides.org Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,37 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC +#+OPTIONS: H:5 num:t toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t + +#+TITLE: Plotting Data +#+AUTHOR: FOSSEE +#+DATE: 2010-09-14 Tue +#+EMAIL: info@fossee.in + +# \author[FOSSEE] {FOSSEE} + +# \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +# \date{} + +* Tutorial Plan +** Creating a simple plot +** Use the buttons on window to study the plot + +* Error if Ipython not installed + +** `ERROR: matplotlib could NOT be imported! Starting normal IPython.` + +* Plot UI + +* Summary + +** Start Ipython with pylab +** Using linspace +** Finding length of sequnces using len. +** Plotting mathematical functions using plot. +** Clearing drawing area using clf +** Using the UI of plot diff -r be96dc6c9743 -r 68813d8d80fb using-plot-interactively/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using-plot-interactively/slides.tex Thu Nov 11 02:28:55 2010 +0530 @@ -0,0 +1,71 @@ +% Created 2010-10-20 Wed 21:57 +\documentclass[presentation]{beamer} +\usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{amssymb} +\usepackage{hyperref} + + +\title{Plotting Data } +\author{FOSSEE} +\date{2010-09-14 Tue} + +\begin{document} + +\maketitle + +\begin{frame} +\frametitle{Tutorial Plan} +\label{sec-1} +\begin{itemize} + +\item Creating a simple plot\\ +\label{sec-1.1}% +\item Use the buttons on window to study the plot\\ +\label{sec-1.2}% +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Error if Ipython not installed} +\label{sec-2} +\begin{itemize} + +\item `ERROR: matplotlib could NOT be imported! Starting normal IPython.`\\ +\label{sec-2.1}% +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Plot UI} +\label{sec-3} +\begin{frame} + \begin{center} + \includegraphics[height=1.0in,width=4.2in]{buttons.png} + \end{center} +\end{frame} + +\frametitle{Summary} +\label{sec-4} +\begin{itemize} + +\item Start Ipython with pylab\\ +\label{sec-4.1}% +\item Using linspace\\ +\label{sec-4.2}% +\item Finding length of sequnces using len.\\ +\label{sec-4.3}% +\item Plotting mathematical functions using plot.\\ +\label{sec-4.4}% +\item Clearing drawing area using clf\\ +\label{sec-4.5}% +\item Using the UI of plot\\ +\label{sec-4.6}% +\end{itemize} % ends low level +\end{frame} + +\end{document} diff -r be96dc6c9743 -r 68813d8d80fb using-plot-interactively/zoom.png Binary file using-plot-interactively/zoom.png has changed diff -r be96dc6c9743 -r 68813d8d80fb using-sage/questions.rst --- a/using-sage/questions.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/using-sage/questions.rst Thu Nov 11 02:28:55 2010 +0530 @@ -64,21 +64,36 @@ Programming ----------- -1. What is the out put of the following code:: +1. Obtain the sum of primes between 1 million and 2 million. + + Answer:: - c1 = Combinations([1, 2, 3, 4]) - c2 = Combinations([1, 2, 4, 3]) + prime_sum = 0 + for i in range(1000001, 2000000, 2): + if is_prime(i): + prime_sum += i + + prime_sum - l1 = c1.list() - l2 = c2.list() + OR + :: + + sum(prime_range(1000000, 2000000)) - for i in l2: - l1.remove(i) +2. ``graphs.WorldMap()`` gives the world map in the form of a + graph. :: - print l2 + G = graphs.WorldMap() + G.vertices() - Answer: [] + + Suppose, I wish to go from India to France by Road, find out the + least number of Visas that I'll have to obtain. + + Answer:: -.. #[[Anoop: add one more question to this part, probably a small - problem asking them to solve it, project euler has problems on - combinations and all]] + G.distance("India", "France") + + + + diff -r be96dc6c9743 -r 68813d8d80fb using-sage/script.rst --- a/using-sage/script.rst Mon Nov 08 02:12:28 2010 +0530 +++ b/using-sage/script.rst Thu Nov 11 02:28:55 2010 +0530 @@ -28,12 +28,8 @@ {{{ show the slide with outline }}} -In this tutorial we shall quickly look at a few examples of the areas -(name the areas, here) in which Sage can be used and how it can be -used. - -.. #[[Anoop: add name of areas and further introduction if needed for - a smooth switch]] +In this tutorial we shall quickly look at a few examples of using Sage +for Linear Algebra, Calculus, Graph Theory and Number theory. {{{ show the slide with Calculus outline }}} @@ -62,9 +58,7 @@ To find the limit from the negative side, we say, :: - lim(1/x, x=0, dir='above') - -.. #[[Anoop: both the above codes are going the same thing isn't it?]] + lim(1/x, x=0, dir='below') Let us now see how to differentiate, using Sage. We shall find the differential of the expression ``exp(sin(x^2))/x`` w.r.t ``x``. We