# HG changeset patch # User Puneeth Chaganti # Date 1291202495 -19800 # Node ID d336983264095e4edf00a017071778bff46745f6 # Parent 88a01948450d1107f3144fc1652ab0171ce7dbf3 Renamed all LOs to match with their names in progress.org. diff -r 88a01948450d -r d33698326409 #symbolics.rst# --- a/#symbolics.rst# Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,343 +0,0 @@ -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 88a01948450d -r d33698326409 accessing-pieces-arrays/questions.rst --- a/accessing-pieces-arrays/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,159 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. Given the array, ``A = array([12, 15, 18, 21])``, how do we access - the element ``18``? - - Answer: ``A[2]`` - -#. Given the array, ``A = array([12, 15, 18, 21])``, what element is - accessed by ``A[1]`` - - Answer: ``15`` - -#. Given the array, ``A = array([12, 15, 18, 21])``, what element is - accessed by ``A[-3]``? - - Answer: ``15`` - -#. Given the array, ``A = array([12, 15, 18, 21])``, how do you change - the element ``15`` to ``51``? - - Answer: ``A[1] = 51`` - -#. Given the array, ``A = array([12, 15, 18, 21])``, what is ``A`` - after the execution of the statement ``A[3] = 24``? - - Answer: ``array([12, 15, 18, 24])`` - -#. Given the array, ``A = array([12, 15, 18, 21])``, what is the - result of the statement, ``A[4] = 24``? - - Answer: IndexError: index out of bounds - -#. Given the array, ``B = array([[12, 15], [18, 21]])``, how do we - access the element ``18``? - - Answer: ``A[0, 0]`` - -#. Given the array, ``B = array([[12, 15], [18, 21]])``, what is the - result of ``B[1]``? - - Answer: ``array([18, 21])`` - -#. Given the array, ``B = array([[12, 15], [18, 21]])``, what is the - result of ``B[1, 1]``? - - Answer: ``21`` - -#. Given the array, ``B = array([[12, 15], [18, 21]])``, what element - is accessed by ``B[-1, -2]``? - - Answer: ``18`` - -#. Given the array, ``B = array([[12, 15], [18, 21]])``, how do you - change the element ``15`` to ``51``? - - Answer: ``B[0, 1] = 51`` - -#. Given the array, ``B = array([[12, 15], [18, 21]])``, what is the - value of B, after executing, ``B[0] = 0``? - - Answer: ``array([[0, 0], [18, 21]])`` - -#. Given the array, - - :: - - B = array([[10, 11, 12, 13], - [20, 21, 22, 23], - [30, 31, 32, 33], - [40, 41, 42, 43]]) - - Obtain the elements, ``[[21, 22], [32, 32]]`` - - Answer: ``B[1:3, 1:3]`` - -#. Given the array, - - :: - - B = array([[10, 11, 12, 13], - [20, 21, 22, 23], - [30, 31, 32, 33], - [40, 41, 42, 43]]) - - Obtain the elements, ``[[10, 13], [30, 33]]`` - - Answer: ``B[::2, ::3]`` - -#. What command is used to read an image file? - - a. imshow - #. imread - #. imopen - #. open - - Answer: ``imread`` - -#. If ``P`` is ``array([12, 13, 14, 15])`` then ``P.shape`` gives - ``(4, 1)``. True or False? - - Answer: False - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Given the array, - :: - - B = array([[10, 11, 12, 13], - [20, 21, 22, 23], - [30, 31, 32, 33], - [40, 41, 42, 43]]) - - Change the array to - :: - - B = array([[10, 11, 10, 11], - [20, 21, 20, 21], - [10, 11, 10, 11], - [20, 21, 20, 21]]) - - using slicing and striding. - - Answer:: - - B[:2, 2:] = B[:2, :2] - B[2:, :2] = B[:2, :2] - B[2:, 2:] = B[:2, :2] - -#. Find out how to display a grayscale image with proper colors. Hint, - use ``?`` on ``imshow``. - - Answer: ``cmap=cm.gray`` - -#. From the image, ``tagore-einstein.png``, - a. show only the face of Einstein. - b. show only the face of Tagore. - - Hint, use ``imread`` to read the image and ``imshow`` to show the - image. Use ``cm.gray`` as ``cmap`` to display the image properly. - - Answer:: - - F = imread('tagore-einstein.png') - imshow(F[:210, 20:180], cmap=cm.gray) - - F = imread('tagore-einstein.png') - imshow(F[30:300, 320:480], cmap=cm.gray) - -.. #[Puneeth: This question contains answer to previous -.. question. Shouldn't be shown at the same time.] - - - diff -r 88a01948450d -r d33698326409 accessing-pieces-arrays/quickref.tex --- a/accessing-pieces-arrays/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,12 +0,0 @@ -\textbf{Accessing parts of arrays} - -\lstinline|C[i-1, j-1]| to access element i, j in C (mxn). -\lstinline|C[i-1]| to access i^{th} row -\lstinline|C[:, j-1]| to access j^{th} column - -Assigning to accessed elements, changes them. - -\lstinline|A[m:n:o]| accesses the rows from \lstinline|m| -to \lstinline|n| (excluded) in steps of \lstinline|o| - -Similarly, \lstinline|C[m:n:o, p:q:r]| diff -r 88a01948450d -r d33698326409 accessing-pieces-arrays/script.rst --- a/accessing-pieces-arrays/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,426 +0,0 @@ -.. Objectives -.. ---------- - - .. By the end of this tutorial, you will be able to: - - .. 1. Access and change individual elements of arrays, both one - .. dimensional and multi-dimensional. - .. 2. Access and change rows and columns of arrays. - .. 3. Access and change other chunks from an array, using slicing - .. and striding. - .. 4. Read images into arrays and perform processing on them, using - .. simple array manipulations. - -.. Prerequisites -.. ------------- - -.. 1. getting started with arrays - -.. #[anand: internal reviewer not mentioned] -.. Author : Puneeth - Internal Reviewer : - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <06-11-2010, Anand, OK> [2010-10-05] - -Script ------- - -{{{ Screen shows welcome slide }}} - -Welcome to the tutorial on accessing pieces of arrays - -{{{ Show the outline for this tutorial }}} - -In this tutorial we shall learn to access individual elements of -arrays, get rows and columns and other chunks of arrays using -slicing and striding. - -{{{ switch back to the terminal }}} - -As usual, we start IPython, using -:: - - ipython -pylab - - -{{ Show the slide with the arrays, A and C }} - -Let us have two arrays, A and C, as the sample arrays that we will -use to work through this tutorial. - -:: - - A = array([12, 23, 34, 45, 56]) - - 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]]) - -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. - -To access, the element 34 in A, we say, - -:: - - 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. - -Now, let us access the element 34 from C. To do this, we say -:: - - 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. - -Now, that we have accessed one element of the array, let us change -it. We shall change the 34 to -34 in both A and C. To do this, we -simply assign the new value after accessing the element. -:: - - A[2] = -34 - C[2, 3] = -34 - -Now that we have accessed and changed a single element, let us -access and change more than one element at a time; first rows and -then columns. - -Let us access one row of C, say the third row. We do it by saying, -:: - - C[2] - -How do we access the last row of C? We could say, -:: - - C[4] - -for the fifth row, or as with lists, use negative indexing and say -:: - - C[-1] - -Now, we could change the last row into all zeros, using either -:: - - C[-1] = [0, 0, 0, 0, 0] - -or - -:: - - C[-1] = 0 - -Now, how do we access one column of C? As with accessing individual -elements, the column is the second parameter to be specified (after -the comma). The first parameter, is replaced with a ``:``. This -specifies that we want all the elements of that dimension, instead of -just one particular element. We access the third column by - -:: - - C[:, 2] - -Following is an exercise that you must do. - -{{ show slide containing Question 1}} - -%%1%% Change the last column of C to zeroes. - -Please, pause the video here. Do the exercises and then continue. - -:: - - C[:, -1] = 0 - -Since A is one dimensional, rows and columns of A don't make much -sense. It has just one row and -:: - - A[:] - -gives the whole of A. - -Following is an exercise that you must do. - -{{ show slide containing Question 2}} - -%%2%% Change ``A`` to ``[11, 12, 13, 14, 15]``. - -Please, pause the video here. Do the exercises and then continue. - -To change A, we say -:: - - A[:] = [11, 12, 13, 14, 15] - -Now, that we know how to access, rows and columns of an array, we -shall learn how to access other pieces of an array. For this -purpose, we will be using image arrays. - -To read an image into an array, we use the ``imread`` command. We -shall use the image ``squares.png`` present in ``/home/fossee``. We -shall first navigate to that path in the OS and see what the image -contains. - -{{{ switch to the browser and show the image }}} - -{{{ switch back to the ipython terminal }}} - -Let us now read the data in ``squares.png`` into the array ``I``. -:: - - I = imread('/home/fossee/squares.png') - -We can see the contents of the image, using the command -``imshow``. We say, -:: - - imshow(I) - -to see what has been read into ``I``. We do not see white and black -because, ``pylab`` has mapped white and black to different -colors. This can be changed by using a different colormap. - -To see that ``I`` is really, just an array, we say, -:: - - I - -at the prompt, and see that an array is displayed. - -To check the dimensions of any array, we can use ``.shape``. We say - -:: - - I.shape - -to get the dimensions of the image. As we can see, ``squares.png`` -has the dimensions of 300x300. - -Our goal for this part of the tutorial would be to get the -top-left quadrant of the image. To do this, we need to access, a -few of the rows and a few of the columns of the array. - -To access, the third column of C, we said, ``C[:, 2]``. Essentially, -we are accessing all the rows in column three of C. Now, let us -modify this to access only the first three rows, of column three -of C. - -We say, -:: - - C[0:3, 2] - -to get the elements of rows indexed from 0 to 3, 3 not included -and column indexed 2. Note that, the index before the colon is -included and the index after it is not included in the slice that -we have obtained. This is very similar to the ``range`` function, -where ``range`` returns a list, in which the upper limit or stop -value is not included. - -Now, if we wish to access the elements of row with index 2, and in -columns indexed 0 to 2 (included), we say, -:: - - C[2, 0:3] - -Following is an exercise that you must do. - -{{ show slide containing Question 3 }} - -%%3%% First, obtain the elements [22, 23] from C. Then, obtain the -elements [11, 21, 31, 41] from C. Finally, obtain the elements [21, -31, 41, 0]. - -Please, pause the video here. Do the exercises and then continue. - -{{ show slide containing Solution 3 }} - -:: - - C[1, 1:3] - -gives the elements [22, 23] -:: - - C[0:4, 0] - -gives the elements [11, 21, 31, 41] -:: - - C[1:5, 0] - -gives the elements [21, 31, 41, 0] - -Note that when specifying ranges, if you are starting from the -beginning or going up-to the end, the corresponding element may be -dropped. So, in the previous example to obtain [11, 21, 31, 41], we -could have simply said, :: - - C[:4, 0] - -and -:: - - C[1:, 0] - -gives the elements [21, 31, 41, 0]. If we skip both the indexes, -we get the slice from end to end, as we already know. - -Following is an exercise that you must do. - -{{ show slide containing Question 4 }} - -%%4%% Obtain the elements [[23, 24], [33, -34]] from C. - -Please, pause the video here. Do the exercises and then continue. - -{{ show slide containing Solution 4 }} - -:: - - C[1:3, 2:4] - -gives us the elements, [[23, 24], [33, -34]]. - -Now, we wish to obtain the top left quarter of the image. How do -we go about doing it? Since, we know the shape of the image to be -300, we know that we need to get the first 150 rows and first 150 -columns. -:: - - I[:150, :150] - -gives us the top-left corner of the image. - -We use the ``imshow`` command to see the slice we obtained in the -form of an image and confirm. -:: - - imshow(I[:150, :150]) - -Following is an exercise that you must do. - -{{ show slide containing Question 5 }} - -%%5%% Obtain the square in the center of the image. - -Please, pause the video here. Do the exercises and then continue. - -{{ show slide containing Solution 5 }} - -:: - - imshow(I[75:225, 75:225]) - -Our next goal is to compress the image, using a very simple -technique to reduce the space that the image takes on disk while -not compromising too heavily on the image quality. The idea is to -drop alternate rows and columns of the image and save it. This way -we will be reducing the data to a fourth of the original data but -losing only so much of visual information. - -We shall first learn the idea of striding using the smaller array -C. Suppose we wish to access only the odd rows and columns (first, -third, fifth). We do this by, -:: - - C[0:5:2, 0:5:2] - -if we wish to be explicit, or simply, -:: - - C[::2, ::2] - -This is very similar to the step specified to the ``range`` -function. It specifies, the jump or step in which to move, while -accessing the elements. If no step is specified, a default value -of 1 is assumed. -:: - - C[1::2, ::2] - -gives the elements, [[21, 23, 0], [41, 43, 0]] - -{{ show slide containing Question 6 }} - -Following is an exercise that you must do. - -%%6%% Obtain the following. -[[12, 0], [42, 0]] -[[12, 13, 14], [0, 0, 0]] - -Please, pause the video here. Do the exercises and then continue. - -{{ show slide containing Solution 6 }} - -:: - - C[::3, 1::3] - -gives the elements [[12, 0], [42, 0]] -:: - - C[::4, 1:4] - -gives the elements [[12, 13, 14], [0, 0, 0]] - -Now, that we know how to stride over an array, we can drop -alternate rows and columns out of the image in I. -:: - - I[::2, ::2] - -To see this image, we say, -:: - - imshow(I[::2, ::2]) - -This does not have much data to notice any real difference, but -notice that the scale has reduced to show that we have dropped -alternate rows and columns. If you notice carefully, you will be -able to observe some blurring near the edges. To notice this -effect more clearly, increase the step to 4. -:: - - imshow(I[::4, ::4]) - -{{{ show summary slide }}} - -That brings us to the end of this tutorial. In this tutorial, we -have learnt to access parts of arrays, specifically individual -elements, rows and columns and larger pieces of arrays. We have -also learnt how to modify arrays, element wise or in larger -pieces. - -{{{ 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! - -.. - Local Variables: - mode: rst - indent-tabs-mode: nil - sentence-end-double-space: nil - fill-column: 70 - End: diff -r 88a01948450d -r d33698326409 accessing-pieces-arrays/slides.org --- a/accessing-pieces-arrays/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,123 +0,0 @@ -#+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 88a01948450d -r d33698326409 accessing-pieces-arrays/slides.org.orig --- a/accessing-pieces-arrays/slides.org.orig Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,123 +0,0 @@ -#+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 88a01948450d -r d33698326409 accessing-pieces-arrays/slides.tex --- a/accessing-pieces-arrays/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,214 +0,0 @@ -% Created 2010-11-02 Tue 17:47 -\documentclass[presentation]{beamer} -\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\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}} - -\title{Accessing parts of arrays} -\author{FOSSEE} -\date{} - -\usetheme{Antibes}\usecolortheme{lily}\useoutertheme{infolines}\setbeamercovered{transparent} -\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} - -\lstset{language=Python} -\begin{lstlisting} -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{lstlisting} -\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} - -\lstset{language=Python} -\begin{lstlisting} -In []: C[:, -1] = 0 -\end{lstlisting} -\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} - -\lstset{language=Python} -\begin{lstlisting} -In []: A[:] = [11, 12, 13, 14, 15] -\end{lstlisting} -\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} - -\lstset{language=Python} -\begin{lstlisting} -In []: C[1, 1:3] -In []: C[0:4, 0] -In []: C[1:5, 0] -\end{lstlisting} -\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} - -\lstset{language=Python} -\begin{lstlisting} -In []: C[1:3, 2:4] -\end{lstlisting} -\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} - -\lstset{language=Python} -\begin{lstlisting} -In []: imshow(I[75:225, 75:225]) -\end{lstlisting} -\end{frame} -\begin{frame}[fragile] -\frametitle{Question 6} -\label{sec-14} - - Obtain the following -\lstset{language=Python} -\begin{lstlisting} -[[12, 0], [42, 0]] -[[12, 13, 14], [0, 0, 0]] -\end{lstlisting} -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 6} -\label{sec-15} - -\lstset{language=Python} -\begin{lstlisting} -In []: C[::3, 1::3] -In []: C[::4, 1:4] -\end{lstlisting} -\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 88a01948450d -r d33698326409 accessing-pieces-arrays/slides.tex.orig --- a/accessing-pieces-arrays/slides.tex.orig Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,199 +0,0 @@ -% 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 88a01948450d -r d33698326409 accessing-pieces-arrays/squares.png Binary file accessing-pieces-arrays/squares.png has changed diff -r 88a01948450d -r d33698326409 accessing-pieces-arrays/tagore-einstein.png Binary file accessing-pieces-arrays/tagore-einstein.png has changed diff -r 88a01948450d -r d33698326409 accessing_parts_of_arrays/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/accessing_parts_of_arrays/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,159 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Given the array, ``A = array([12, 15, 18, 21])``, how do we access + the element ``18``? + + Answer: ``A[2]`` + +#. Given the array, ``A = array([12, 15, 18, 21])``, what element is + accessed by ``A[1]`` + + Answer: ``15`` + +#. Given the array, ``A = array([12, 15, 18, 21])``, what element is + accessed by ``A[-3]``? + + Answer: ``15`` + +#. Given the array, ``A = array([12, 15, 18, 21])``, how do you change + the element ``15`` to ``51``? + + Answer: ``A[1] = 51`` + +#. Given the array, ``A = array([12, 15, 18, 21])``, what is ``A`` + after the execution of the statement ``A[3] = 24``? + + Answer: ``array([12, 15, 18, 24])`` + +#. Given the array, ``A = array([12, 15, 18, 21])``, what is the + result of the statement, ``A[4] = 24``? + + Answer: IndexError: index out of bounds + +#. Given the array, ``B = array([[12, 15], [18, 21]])``, how do we + access the element ``18``? + + Answer: ``A[0, 0]`` + +#. Given the array, ``B = array([[12, 15], [18, 21]])``, what is the + result of ``B[1]``? + + Answer: ``array([18, 21])`` + +#. Given the array, ``B = array([[12, 15], [18, 21]])``, what is the + result of ``B[1, 1]``? + + Answer: ``21`` + +#. Given the array, ``B = array([[12, 15], [18, 21]])``, what element + is accessed by ``B[-1, -2]``? + + Answer: ``18`` + +#. Given the array, ``B = array([[12, 15], [18, 21]])``, how do you + change the element ``15`` to ``51``? + + Answer: ``B[0, 1] = 51`` + +#. Given the array, ``B = array([[12, 15], [18, 21]])``, what is the + value of B, after executing, ``B[0] = 0``? + + Answer: ``array([[0, 0], [18, 21]])`` + +#. Given the array, + + :: + + B = array([[10, 11, 12, 13], + [20, 21, 22, 23], + [30, 31, 32, 33], + [40, 41, 42, 43]]) + + Obtain the elements, ``[[21, 22], [32, 32]]`` + + Answer: ``B[1:3, 1:3]`` + +#. Given the array, + + :: + + B = array([[10, 11, 12, 13], + [20, 21, 22, 23], + [30, 31, 32, 33], + [40, 41, 42, 43]]) + + Obtain the elements, ``[[10, 13], [30, 33]]`` + + Answer: ``B[::2, ::3]`` + +#. What command is used to read an image file? + + a. imshow + #. imread + #. imopen + #. open + + Answer: ``imread`` + +#. If ``P`` is ``array([12, 13, 14, 15])`` then ``P.shape`` gives + ``(4, 1)``. True or False? + + Answer: False + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Given the array, + :: + + B = array([[10, 11, 12, 13], + [20, 21, 22, 23], + [30, 31, 32, 33], + [40, 41, 42, 43]]) + + Change the array to + :: + + B = array([[10, 11, 10, 11], + [20, 21, 20, 21], + [10, 11, 10, 11], + [20, 21, 20, 21]]) + + using slicing and striding. + + Answer:: + + B[:2, 2:] = B[:2, :2] + B[2:, :2] = B[:2, :2] + B[2:, 2:] = B[:2, :2] + +#. Find out how to display a grayscale image with proper colors. Hint, + use ``?`` on ``imshow``. + + Answer: ``cmap=cm.gray`` + +#. From the image, ``tagore-einstein.png``, + a. show only the face of Einstein. + b. show only the face of Tagore. + + Hint, use ``imread`` to read the image and ``imshow`` to show the + image. Use ``cm.gray`` as ``cmap`` to display the image properly. + + Answer:: + + F = imread('tagore-einstein.png') + imshow(F[:210, 20:180], cmap=cm.gray) + + F = imread('tagore-einstein.png') + imshow(F[30:300, 320:480], cmap=cm.gray) + +.. #[Puneeth: This question contains answer to previous +.. question. Shouldn't be shown at the same time.] + + + diff -r 88a01948450d -r d33698326409 accessing_parts_of_arrays/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/accessing_parts_of_arrays/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,12 @@ +\textbf{Accessing parts of arrays} + +\lstinline|C[i-1, j-1]| to access element i, j in C (mxn). +\lstinline|C[i-1]| to access i^{th} row +\lstinline|C[:, j-1]| to access j^{th} column + +Assigning to accessed elements, changes them. + +\lstinline|A[m:n:o]| accesses the rows from \lstinline|m| +to \lstinline|n| (excluded) in steps of \lstinline|o| + +Similarly, \lstinline|C[m:n:o, p:q:r]| diff -r 88a01948450d -r d33698326409 accessing_parts_of_arrays/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/accessing_parts_of_arrays/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,426 @@ +.. Objectives +.. ---------- + + .. By the end of this tutorial, you will be able to: + + .. 1. Access and change individual elements of arrays, both one + .. dimensional and multi-dimensional. + .. 2. Access and change rows and columns of arrays. + .. 3. Access and change other chunks from an array, using slicing + .. and striding. + .. 4. Read images into arrays and perform processing on them, using + .. simple array manipulations. + +.. Prerequisites +.. ------------- + +.. 1. getting started with arrays + +.. #[anand: internal reviewer not mentioned] +.. Author : Puneeth + Internal Reviewer : + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <06-11-2010, Anand, OK> [2010-10-05] + +Script +------ + +{{{ Screen shows welcome slide }}} + +Welcome to the tutorial on accessing pieces of arrays + +{{{ Show the outline for this tutorial }}} + +In this tutorial we shall learn to access individual elements of +arrays, get rows and columns and other chunks of arrays using +slicing and striding. + +{{{ switch back to the terminal }}} + +As usual, we start IPython, using +:: + + ipython -pylab + + +{{ Show the slide with the arrays, A and C }} + +Let us have two arrays, A and C, as the sample arrays that we will +use to work through this tutorial. + +:: + + A = array([12, 23, 34, 45, 56]) + + 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]]) + +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. + +To access, the element 34 in A, we say, + +:: + + 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. + +Now, let us access the element 34 from C. To do this, we say +:: + + 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. + +Now, that we have accessed one element of the array, let us change +it. We shall change the 34 to -34 in both A and C. To do this, we +simply assign the new value after accessing the element. +:: + + A[2] = -34 + C[2, 3] = -34 + +Now that we have accessed and changed a single element, let us +access and change more than one element at a time; first rows and +then columns. + +Let us access one row of C, say the third row. We do it by saying, +:: + + C[2] + +How do we access the last row of C? We could say, +:: + + C[4] + +for the fifth row, or as with lists, use negative indexing and say +:: + + C[-1] + +Now, we could change the last row into all zeros, using either +:: + + C[-1] = [0, 0, 0, 0, 0] + +or + +:: + + C[-1] = 0 + +Now, how do we access one column of C? As with accessing individual +elements, the column is the second parameter to be specified (after +the comma). The first parameter, is replaced with a ``:``. This +specifies that we want all the elements of that dimension, instead of +just one particular element. We access the third column by + +:: + + C[:, 2] + +Following is an exercise that you must do. + +{{ show slide containing Question 1}} + +%%1%% Change the last column of C to zeroes. + +Please, pause the video here. Do the exercises and then continue. + +:: + + C[:, -1] = 0 + +Since A is one dimensional, rows and columns of A don't make much +sense. It has just one row and +:: + + A[:] + +gives the whole of A. + +Following is an exercise that you must do. + +{{ show slide containing Question 2}} + +%%2%% Change ``A`` to ``[11, 12, 13, 14, 15]``. + +Please, pause the video here. Do the exercises and then continue. + +To change A, we say +:: + + A[:] = [11, 12, 13, 14, 15] + +Now, that we know how to access, rows and columns of an array, we +shall learn how to access other pieces of an array. For this +purpose, we will be using image arrays. + +To read an image into an array, we use the ``imread`` command. We +shall use the image ``squares.png`` present in ``/home/fossee``. We +shall first navigate to that path in the OS and see what the image +contains. + +{{{ switch to the browser and show the image }}} + +{{{ switch back to the ipython terminal }}} + +Let us now read the data in ``squares.png`` into the array ``I``. +:: + + I = imread('/home/fossee/squares.png') + +We can see the contents of the image, using the command +``imshow``. We say, +:: + + imshow(I) + +to see what has been read into ``I``. We do not see white and black +because, ``pylab`` has mapped white and black to different +colors. This can be changed by using a different colormap. + +To see that ``I`` is really, just an array, we say, +:: + + I + +at the prompt, and see that an array is displayed. + +To check the dimensions of any array, we can use ``.shape``. We say + +:: + + I.shape + +to get the dimensions of the image. As we can see, ``squares.png`` +has the dimensions of 300x300. + +Our goal for this part of the tutorial would be to get the +top-left quadrant of the image. To do this, we need to access, a +few of the rows and a few of the columns of the array. + +To access, the third column of C, we said, ``C[:, 2]``. Essentially, +we are accessing all the rows in column three of C. Now, let us +modify this to access only the first three rows, of column three +of C. + +We say, +:: + + C[0:3, 2] + +to get the elements of rows indexed from 0 to 3, 3 not included +and column indexed 2. Note that, the index before the colon is +included and the index after it is not included in the slice that +we have obtained. This is very similar to the ``range`` function, +where ``range`` returns a list, in which the upper limit or stop +value is not included. + +Now, if we wish to access the elements of row with index 2, and in +columns indexed 0 to 2 (included), we say, +:: + + C[2, 0:3] + +Following is an exercise that you must do. + +{{ show slide containing Question 3 }} + +%%3%% First, obtain the elements [22, 23] from C. Then, obtain the +elements [11, 21, 31, 41] from C. Finally, obtain the elements [21, +31, 41, 0]. + +Please, pause the video here. Do the exercises and then continue. + +{{ show slide containing Solution 3 }} + +:: + + C[1, 1:3] + +gives the elements [22, 23] +:: + + C[0:4, 0] + +gives the elements [11, 21, 31, 41] +:: + + C[1:5, 0] + +gives the elements [21, 31, 41, 0] + +Note that when specifying ranges, if you are starting from the +beginning or going up-to the end, the corresponding element may be +dropped. So, in the previous example to obtain [11, 21, 31, 41], we +could have simply said, :: + + C[:4, 0] + +and +:: + + C[1:, 0] + +gives the elements [21, 31, 41, 0]. If we skip both the indexes, +we get the slice from end to end, as we already know. + +Following is an exercise that you must do. + +{{ show slide containing Question 4 }} + +%%4%% Obtain the elements [[23, 24], [33, -34]] from C. + +Please, pause the video here. Do the exercises and then continue. + +{{ show slide containing Solution 4 }} + +:: + + C[1:3, 2:4] + +gives us the elements, [[23, 24], [33, -34]]. + +Now, we wish to obtain the top left quarter of the image. How do +we go about doing it? Since, we know the shape of the image to be +300, we know that we need to get the first 150 rows and first 150 +columns. +:: + + I[:150, :150] + +gives us the top-left corner of the image. + +We use the ``imshow`` command to see the slice we obtained in the +form of an image and confirm. +:: + + imshow(I[:150, :150]) + +Following is an exercise that you must do. + +{{ show slide containing Question 5 }} + +%%5%% Obtain the square in the center of the image. + +Please, pause the video here. Do the exercises and then continue. + +{{ show slide containing Solution 5 }} + +:: + + imshow(I[75:225, 75:225]) + +Our next goal is to compress the image, using a very simple +technique to reduce the space that the image takes on disk while +not compromising too heavily on the image quality. The idea is to +drop alternate rows and columns of the image and save it. This way +we will be reducing the data to a fourth of the original data but +losing only so much of visual information. + +We shall first learn the idea of striding using the smaller array +C. Suppose we wish to access only the odd rows and columns (first, +third, fifth). We do this by, +:: + + C[0:5:2, 0:5:2] + +if we wish to be explicit, or simply, +:: + + C[::2, ::2] + +This is very similar to the step specified to the ``range`` +function. It specifies, the jump or step in which to move, while +accessing the elements. If no step is specified, a default value +of 1 is assumed. +:: + + C[1::2, ::2] + +gives the elements, [[21, 23, 0], [41, 43, 0]] + +{{ show slide containing Question 6 }} + +Following is an exercise that you must do. + +%%6%% Obtain the following. +[[12, 0], [42, 0]] +[[12, 13, 14], [0, 0, 0]] + +Please, pause the video here. Do the exercises and then continue. + +{{ show slide containing Solution 6 }} + +:: + + C[::3, 1::3] + +gives the elements [[12, 0], [42, 0]] +:: + + C[::4, 1:4] + +gives the elements [[12, 13, 14], [0, 0, 0]] + +Now, that we know how to stride over an array, we can drop +alternate rows and columns out of the image in I. +:: + + I[::2, ::2] + +To see this image, we say, +:: + + imshow(I[::2, ::2]) + +This does not have much data to notice any real difference, but +notice that the scale has reduced to show that we have dropped +alternate rows and columns. If you notice carefully, you will be +able to observe some blurring near the edges. To notice this +effect more clearly, increase the step to 4. +:: + + imshow(I[::4, ::4]) + +{{{ show summary slide }}} + +That brings us to the end of this tutorial. In this tutorial, we +have learnt to access parts of arrays, specifically individual +elements, rows and columns and larger pieces of arrays. We have +also learnt how to modify arrays, element wise or in larger +pieces. + +{{{ 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! + +.. + Local Variables: + mode: rst + indent-tabs-mode: nil + sentence-end-double-space: nil + fill-column: 70 + End: diff -r 88a01948450d -r d33698326409 accessing_parts_of_arrays/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/accessing_parts_of_arrays/slides.org Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 accessing_parts_of_arrays/slides.org.orig --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/accessing_parts_of_arrays/slides.org.orig Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 accessing_parts_of_arrays/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/accessing_parts_of_arrays/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,214 @@ +% Created 2010-11-02 Tue 17:47 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\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}} + +\title{Accessing parts of arrays} +\author{FOSSEE} +\date{} + +\usetheme{Antibes}\usecolortheme{lily}\useoutertheme{infolines}\setbeamercovered{transparent} +\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} + +\lstset{language=Python} +\begin{lstlisting} +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{lstlisting} +\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} + +\lstset{language=Python} +\begin{lstlisting} +In []: C[:, -1] = 0 +\end{lstlisting} +\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} + +\lstset{language=Python} +\begin{lstlisting} +In []: A[:] = [11, 12, 13, 14, 15] +\end{lstlisting} +\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} + +\lstset{language=Python} +\begin{lstlisting} +In []: C[1, 1:3] +In []: C[0:4, 0] +In []: C[1:5, 0] +\end{lstlisting} +\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} + +\lstset{language=Python} +\begin{lstlisting} +In []: C[1:3, 2:4] +\end{lstlisting} +\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} + +\lstset{language=Python} +\begin{lstlisting} +In []: imshow(I[75:225, 75:225]) +\end{lstlisting} +\end{frame} +\begin{frame}[fragile] +\frametitle{Question 6} +\label{sec-14} + + Obtain the following +\lstset{language=Python} +\begin{lstlisting} +[[12, 0], [42, 0]] +[[12, 13, 14], [0, 0, 0]] +\end{lstlisting} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 6} +\label{sec-15} + +\lstset{language=Python} +\begin{lstlisting} +In []: C[::3, 1::3] +In []: C[::4, 1:4] +\end{lstlisting} +\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 88a01948450d -r d33698326409 accessing_parts_of_arrays/slides.tex.orig --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/accessing_parts_of_arrays/slides.tex.orig Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 accessing_parts_of_arrays/squares.png Binary file accessing_parts_of_arrays/squares.png has changed diff -r 88a01948450d -r d33698326409 accessing_parts_of_arrays/tagore-einstein.png Binary file accessing_parts_of_arrays/tagore-einstein.png has changed diff -r 88a01948450d -r d33698326409 additional_features_of_ipython/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_features_of_ipython/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,134 @@ +Objective Questions +------------------- + + 1. How do you retrieve the recent 5 commands + + a. ``%hist`` + #. ``%hist -5`` + #. ``%hist 5`` + #. ``%hist 5-10`` + + Answer: ``%hist 5`` + + 2. If there were 20 commands typed and ``%hist`` is used. How many commands + will be displayed. + + a. 10 + #. 20 + #. 21 + #. 19 + + Answer: 21 + +.. #[Amit: I really don't get the question below] + + 3. is ``%hist`` considered as a command + + a. True + #. False + + Answer: True + + 4. how do you retreive the commands from 20 to 50 (inclusive of 20 and 50) + + a. ``%hist 20 50`` + #. ``%hist 19 50`` + #. ``%hist 19 51`` + #. ``%hist 21 50`` + + Answer: ``%hist 20 50`` + + 5. What does the ``%hist 2 5 7`` command do + + a. lists the second, fifth and seventh commands + #. lists the commands from 2 to 5 and the seventh command + #. raises an error + #. lists the commands 2 to 7 + + Answer: raises an error + + 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 + #. 50 + #. 40 + + Answer: 40 + + 7. How do you save the lines 2 3 4 5 7 9 10 11 + + a. ``%save filepath 2-5 7 9-11`` + #. ``%save filepath 2-11`` + #. ``%save filepath`` + #. ``%save 2-5 7 9 10 11`` + + Answer: ``%save filepath 2-5 7 9-11`` + + 8. You are working in /home/user. Where is the file saved when you do + ``%save hello.py 1-3`` + + a. /home/user/hello.py + #. /hello.py + #. /home/hello.py + #. /home/user/ipython/hello.py + + Answer: /home/user/hello.py + + 9. Which lines are saved by the command ``%save filepath 2-5 7 1`` and in + which order + + a. 2 3 4 5 7 1 + #. 1 2 3 4 5 6 7 + #. 2 5 7 1 + #. 1 2 5 7 + + Answer: a + +10. What happens when ``%save filepath line_numbers`` is used and a file + already exists in that path. + + a. It is overwritten + #. The commands are added to the file + #. It raises an error + #. A prompt to confirm overwriting is displayed + + Answer: A prompt to confirm overwriting is displayed + + 11. Read through the documentation of ``%hist`` and find its alternative name + + Answer: ``%history`` + + 12. Are ``%run /home/user/saved.py`` and ``%run /home/user/saved`` the same + + a. Yes + #. No + + Answer: Yes + + 13. The file hello.py contains only one command ``x = x + 1``. What happens + when you do ``%run hello.py`` + + Answer: Raises a nameerror + + 14. The file hello.py contains only one command ``x = x + 1``. If value of x + is 5 and what does ``%run -i hello.py`` do. + + a. raises an error + #. increments value of x by 1 + #. 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 88a01948450d -r d33698326409 additional_features_of_ipython/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_features_of_ipython/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,15 @@ +accessing history:\\ +{\ex \lstinline| \%hist|} + +accessing particular line of history:\\ +{\ex \lstinline| \%hist line_number|} + +accessing particular range of history:\\ +{\ex \lstinline| \%hist start_line stop_line|} + +saving history to a file:\\ +{\ex \lstinline| \%save file_path line_numbers|} + +running a script:\\ +{\ex \lstinline| \%run -i file_path|} + diff -r 88a01948450d -r d33698326409 additional_features_of_ipython/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_features_of_ipython/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,219 @@ +.. Objectives +.. ---------- + +.. By the end of this tutorial you will be able to + +.. #. Retrieve your ipython history +.. #. View a part of the history +.. #. Save a part of your history to a file. +.. #. Run a script from within ipython + + +.. Prerequisites +.. ------------- + +.. 1. Embellishing Plots + +.. Author : Nishanth Amuluru + Internal Reviewer : Amit + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <15-11-2010, Anand, OK> [2010-10-05] + +Script +------ + +Hello friends and welcome to the tutorial on Additional Features of IPython + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall look at additional features of IPython that help us +to retreive the commands that we type on the interpreter and then save them +into a file and run it. + +Let us start ipython with pylab loaded, by typing +:: + + $ ipython -pylab + +on the terminal + +{{{ shift to terminal and type ipython -pylab }}} + +We shall first make a plot and then view the history and save it. +:: + + x = linspace(-2*pi, 2*pi, 100) + plot(x, xsinx(x)) + +xsin(x) is actually x * sin(x) +:: + + plot(x, x*sin(x)) + plot(x, sin(x)) + xlabel("x") + ylabel("$f(x)$") + title("x and xsin") + +We now have the plot. Let us look at the commands that we have typed in. The +history can be retreived by using =%hist= command. Type +:: + + %hist + +As you can see, it displays a list of recent commands that we typed. Every +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 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. 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 commands to be displayed, we pass the number as an argument +to =%hist= command. Hence +:: + + %hist 5 + +displays the recent 5 commands, inclusive of the =%hist= command. +The default number is 40. + +{{{ Pause here and try out the following exercises }}} + +%% 1 %% Read through the documentation of %hist and find out how to + list all the commands between 5 and 10 + +{{{ continue from paused state }}} + +As we can see from =%hist= documentation, +:: + + %hist 5 10 + +displays the commands from 5 to 10 + +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 +:: + + %hist + + +{{{ 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 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. + +So we need first third to sixth and the eigthth command for our program. +Hence the syntax of =%save= is +:: + + %save /home/fossee/plot_script.py 1 3-6 8 + +{{{ point to the output of the command }}} + +The command saves first and then third to sixth and eighth lines of code into +the specified file. + +The first argument to %save is the path of file to save the commands and the +arguments there after are the commands to be saved in the given order. + +{{{ goto the file and open it and show it }}} + +{{{ Pause here and try out the following exercises }}} + +%% 2 %% Change the label on y-axis to "y" and save the lines of code + accordingly + +{{{ continue from paused state }}} + +we use the command =ylabel= on interpreter as +:: + + ylabel("y") + +and then do +:: + + %save /home/fossee/example_plot.py 1 3-6 10 + +Now that we have the required lines of code in a file, let us learn how to run +the file as a python script. + +We use the IPython magic command =%run= to do this. Type +:: + + %run -i /home/fossee/plot_script.py + +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 +:: + + show() + +to show the plot. + +{{{ Pause here and try out the following exercises }}} + +%% 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 +:: + + %hist 20 + +Then save the script using +:: + + %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. + +The reason for including a -i after run is to tell the interpreter that if any +name is not found in script, search for it in the interpreter. Hence all these +sin, plot, pi and show which are not available in script, are taken from the +interpreter and used to run the script. + +{{{ Pause here and try out the following exercises }}} + +%% 4 %% Run the script without using the -i option. Do you find any difference? + +{{{ continue from paused state }}} + +We see that it raises NameError saying that the name linspace is not found. + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have looked at + + * Retreiving history using =%hist= command + * Vieweing only a part of history by passing an argument to %hist + * saving the required lines of code in required order using %save + * using %run -i command to run the saved script + +{{{ 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 88a01948450d -r d33698326409 additional_features_of_ipython/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_features_of_ipython/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,90 @@ +#+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: Additional Features of =ipython= +#+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 + + Retrieving ipython history + + Viewing a part of the history + + Saving (relevant) parts of the history to a file + + Running a script from within ipython +* Question 1 + Read through the documentation of ~%hist~ and find out how to list + all the commands between 5 and 10 +* Solution 1 + #+begin_src python + In []: %hist 5 10 + #+end_src +* Question 2 + Change the label on y-axis to "y" and save the lines of code + accordingly +* Solution 2 + #+begin_src python + In []: ylabel("y") + In []: %save /home/fossee/example_plot.py 1 3-6 10 + #+end_src +* Question 3 + Use =%hist= and =%save= and create a script that has show in it and + run it to produce and show the plot. + +* Solution 3 + #+begin_src python + In []: %hist 20 + + In []: %save /home/fossee/show_included.py 1 3-6 8 10 13 + In []: %run -i /home/fossee/show_included.py + #+end_src +* Question 4 + Run the script without using the -i option. Do you find any + difference? +* Solution 4 + We see that it raises ~NameError~ saying the name ~linspace~ is not + found. +* Summary + + Retreiving history using =%hist= command + + Vieweing only a part of history by passing an argument to %hist + + Saving the required lines of code in required order using %save + + Using %run -i command to run the saved script + +* 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 88a01948450d -r d33698326409 additional_features_of_ipython/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_features_of_ipython/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,149 @@ +% Created 2010-10-10 Sun 17:30 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\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}} + +\title{Additional Features of \texttt{ipython}} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Retrieving ipython history +\item Viewing a part of the history +\item Saving (relevant) parts of the history to a file +\item Running a script from within ipython +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Read through the documentation of \texttt{\%hist} and find out how to list + all the commands between 5 and 10 +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +In []: %hist 5 10 +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + Change the label on y-axis to ``y'' and save the lines of code + accordingly +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} + +\lstset{language=Python} +\begin{lstlisting} +In []: ylabel("y") +In []: %save /home/fossee/example_plot.py 1 3-6 10 +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + + Use \texttt{\%hist} and \texttt{\%save} and create a script that has show in it and + run it to produce and show the plot. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 3} +\label{sec-7} + +\lstset{language=Python} +\begin{lstlisting} +In []: %hist 20 + +In []: %save /home/fossee/show_included.py 1 3-6 8 10 13 +In []: %run -i /home/fossee/show_included.py +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-8} + + Run the script without using the -i option. Do you find any + difference? +\end{frame} +\begin{frame} +\frametitle{Solution 4} +\label{sec-9} + + We see that it raises \texttt{NameError} saying the name \texttt{linspace} is not + found. +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-10} + +\begin{itemize} +\item Retreiving history using \texttt{\%hist} command +\item Vieweing only a part of history by passing an argument to \%hist +\item Saving the required lines of code in required order using \%save +\item Using \%run -i command to run the saved script +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-11} + + \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 88a01948450d -r d33698326409 additional_ipython/questions.rst --- a/additional_ipython/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,134 +0,0 @@ -Objective Questions -------------------- - - 1. How do you retrieve the recent 5 commands - - a. ``%hist`` - #. ``%hist -5`` - #. ``%hist 5`` - #. ``%hist 5-10`` - - Answer: ``%hist 5`` - - 2. If there were 20 commands typed and ``%hist`` is used. How many commands - will be displayed. - - a. 10 - #. 20 - #. 21 - #. 19 - - Answer: 21 - -.. #[Amit: I really don't get the question below] - - 3. is ``%hist`` considered as a command - - a. True - #. False - - Answer: True - - 4. how do you retreive the commands from 20 to 50 (inclusive of 20 and 50) - - a. ``%hist 20 50`` - #. ``%hist 19 50`` - #. ``%hist 19 51`` - #. ``%hist 21 50`` - - Answer: ``%hist 20 50`` - - 5. What does the ``%hist 2 5 7`` command do - - a. lists the second, fifth and seventh commands - #. lists the commands from 2 to 5 and the seventh command - #. raises an error - #. lists the commands 2 to 7 - - Answer: raises an error - - 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 - #. 50 - #. 40 - - Answer: 40 - - 7. How do you save the lines 2 3 4 5 7 9 10 11 - - a. ``%save filepath 2-5 7 9-11`` - #. ``%save filepath 2-11`` - #. ``%save filepath`` - #. ``%save 2-5 7 9 10 11`` - - Answer: ``%save filepath 2-5 7 9-11`` - - 8. You are working in /home/user. Where is the file saved when you do - ``%save hello.py 1-3`` - - a. /home/user/hello.py - #. /hello.py - #. /home/hello.py - #. /home/user/ipython/hello.py - - Answer: /home/user/hello.py - - 9. Which lines are saved by the command ``%save filepath 2-5 7 1`` and in - which order - - a. 2 3 4 5 7 1 - #. 1 2 3 4 5 6 7 - #. 2 5 7 1 - #. 1 2 5 7 - - Answer: a - -10. What happens when ``%save filepath line_numbers`` is used and a file - already exists in that path. - - a. It is overwritten - #. The commands are added to the file - #. It raises an error - #. A prompt to confirm overwriting is displayed - - Answer: A prompt to confirm overwriting is displayed - - 11. Read through the documentation of ``%hist`` and find its alternative name - - Answer: ``%history`` - - 12. Are ``%run /home/user/saved.py`` and ``%run /home/user/saved`` the same - - a. Yes - #. No - - Answer: Yes - - 13. The file hello.py contains only one command ``x = x + 1``. What happens - when you do ``%run hello.py`` - - Answer: Raises a nameerror - - 14. The file hello.py contains only one command ``x = x + 1``. If value of x - is 5 and what does ``%run -i hello.py`` do. - - a. raises an error - #. increments value of x by 1 - #. 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 88a01948450d -r d33698326409 additional_ipython/quickref.tex --- a/additional_ipython/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,15 +0,0 @@ -accessing history:\\ -{\ex \lstinline| \%hist|} - -accessing particular line of history:\\ -{\ex \lstinline| \%hist line_number|} - -accessing particular range of history:\\ -{\ex \lstinline| \%hist start_line stop_line|} - -saving history to a file:\\ -{\ex \lstinline| \%save file_path line_numbers|} - -running a script:\\ -{\ex \lstinline| \%run -i file_path|} - diff -r 88a01948450d -r d33698326409 additional_ipython/script.rst --- a/additional_ipython/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,219 +0,0 @@ -.. Objectives -.. ---------- - -.. By the end of this tutorial you will be able to - -.. #. Retrieve your ipython history -.. #. View a part of the history -.. #. Save a part of your history to a file. -.. #. Run a script from within ipython - - -.. Prerequisites -.. ------------- - -.. 1. Embellishing Plots - -.. Author : Nishanth Amuluru - Internal Reviewer : Amit - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <15-11-2010, Anand, OK> [2010-10-05] - -Script ------- - -Hello friends and welcome to the tutorial on Additional Features of IPython - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall look at additional features of IPython that help us -to retreive the commands that we type on the interpreter and then save them -into a file and run it. - -Let us start ipython with pylab loaded, by typing -:: - - $ ipython -pylab - -on the terminal - -{{{ shift to terminal and type ipython -pylab }}} - -We shall first make a plot and then view the history and save it. -:: - - x = linspace(-2*pi, 2*pi, 100) - plot(x, xsinx(x)) - -xsin(x) is actually x * sin(x) -:: - - plot(x, x*sin(x)) - plot(x, sin(x)) - xlabel("x") - ylabel("$f(x)$") - title("x and xsin") - -We now have the plot. Let us look at the commands that we have typed in. The -history can be retreived by using =%hist= command. Type -:: - - %hist - -As you can see, it displays a list of recent commands that we typed. Every -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 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. 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 commands to be displayed, we pass the number as an argument -to =%hist= command. Hence -:: - - %hist 5 - -displays the recent 5 commands, inclusive of the =%hist= command. -The default number is 40. - -{{{ Pause here and try out the following exercises }}} - -%% 1 %% Read through the documentation of %hist and find out how to - list all the commands between 5 and 10 - -{{{ continue from paused state }}} - -As we can see from =%hist= documentation, -:: - - %hist 5 10 - -displays the commands from 5 to 10 - -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 -:: - - %hist - - -{{{ 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 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. - -So we need first third to sixth and the eigthth command for our program. -Hence the syntax of =%save= is -:: - - %save /home/fossee/plot_script.py 1 3-6 8 - -{{{ point to the output of the command }}} - -The command saves first and then third to sixth and eighth lines of code into -the specified file. - -The first argument to %save is the path of file to save the commands and the -arguments there after are the commands to be saved in the given order. - -{{{ goto the file and open it and show it }}} - -{{{ Pause here and try out the following exercises }}} - -%% 2 %% Change the label on y-axis to "y" and save the lines of code - accordingly - -{{{ continue from paused state }}} - -we use the command =ylabel= on interpreter as -:: - - ylabel("y") - -and then do -:: - - %save /home/fossee/example_plot.py 1 3-6 10 - -Now that we have the required lines of code in a file, let us learn how to run -the file as a python script. - -We use the IPython magic command =%run= to do this. Type -:: - - %run -i /home/fossee/plot_script.py - -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 -:: - - show() - -to show the plot. - -{{{ Pause here and try out the following exercises }}} - -%% 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 -:: - - %hist 20 - -Then save the script using -:: - - %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. - -The reason for including a -i after run is to tell the interpreter that if any -name is not found in script, search for it in the interpreter. Hence all these -sin, plot, pi and show which are not available in script, are taken from the -interpreter and used to run the script. - -{{{ Pause here and try out the following exercises }}} - -%% 4 %% Run the script without using the -i option. Do you find any difference? - -{{{ continue from paused state }}} - -We see that it raises NameError saying that the name linspace is not found. - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial. -we have looked at - - * Retreiving history using =%hist= command - * Vieweing only a part of history by passing an argument to %hist - * saving the required lines of code in required order using %save - * using %run -i command to run the saved script - -{{{ 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 88a01948450d -r d33698326409 additional_ipython/slides.org --- a/additional_ipython/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,90 +0,0 @@ -#+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: Additional Features of =ipython= -#+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 - + Retrieving ipython history - + Viewing a part of the history - + Saving (relevant) parts of the history to a file - + Running a script from within ipython -* Question 1 - Read through the documentation of ~%hist~ and find out how to list - all the commands between 5 and 10 -* Solution 1 - #+begin_src python - In []: %hist 5 10 - #+end_src -* Question 2 - Change the label on y-axis to "y" and save the lines of code - accordingly -* Solution 2 - #+begin_src python - In []: ylabel("y") - In []: %save /home/fossee/example_plot.py 1 3-6 10 - #+end_src -* Question 3 - Use =%hist= and =%save= and create a script that has show in it and - run it to produce and show the plot. - -* Solution 3 - #+begin_src python - In []: %hist 20 - - In []: %save /home/fossee/show_included.py 1 3-6 8 10 13 - In []: %run -i /home/fossee/show_included.py - #+end_src -* Question 4 - Run the script without using the -i option. Do you find any - difference? -* Solution 4 - We see that it raises ~NameError~ saying the name ~linspace~ is not - found. -* Summary - + Retreiving history using =%hist= command - + Vieweing only a part of history by passing an argument to %hist - + Saving the required lines of code in required order using %save - + Using %run -i command to run the saved script - -* 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 88a01948450d -r d33698326409 additional_ipython/slides.tex --- a/additional_ipython/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,149 +0,0 @@ -% Created 2010-10-10 Sun 17:30 -\documentclass[presentation]{beamer} -\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\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}} - -\title{Additional Features of \texttt{ipython}} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Retrieving ipython history -\item Viewing a part of the history -\item Saving (relevant) parts of the history to a file -\item Running a script from within ipython -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Question 1} -\label{sec-2} - - Read through the documentation of \texttt{\%hist} and find out how to list - all the commands between 5 and 10 -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 1} -\label{sec-3} - -\lstset{language=Python} -\begin{lstlisting} -In []: %hist 5 10 -\end{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Question 2} -\label{sec-4} - - Change the label on y-axis to ``y'' and save the lines of code - accordingly -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 2} -\label{sec-5} - -\lstset{language=Python} -\begin{lstlisting} -In []: ylabel("y") -In []: %save /home/fossee/example_plot.py 1 3-6 10 -\end{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Question 3} -\label{sec-6} - - Use \texttt{\%hist} and \texttt{\%save} and create a script that has show in it and - run it to produce and show the plot. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 3} -\label{sec-7} - -\lstset{language=Python} -\begin{lstlisting} -In []: %hist 20 - -In []: %save /home/fossee/show_included.py 1 3-6 8 10 13 -In []: %run -i /home/fossee/show_included.py -\end{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Question 4} -\label{sec-8} - - Run the script without using the -i option. Do you find any - difference? -\end{frame} -\begin{frame} -\frametitle{Solution 4} -\label{sec-9} - - We see that it raises \texttt{NameError} saying the name \texttt{linspace} is not - found. -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-10} - -\begin{itemize} -\item Retreiving history using \texttt{\%hist} command -\item Vieweing only a part of history by passing an argument to \%hist -\item Saving the required lines of code in required order using \%save -\item Using \%run -i command to run the saved script -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-11} - - \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 88a01948450d -r d33698326409 advanced-features-functions/questions.rst --- a/advanced-features-functions/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,109 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. All arguments of a function cannot have default values. True or - False? - - Answer: False - -#. When calling a function, the arguments - - 1. should always be in the order in which they are defined. - #. can be in any order - #. only keyword arguments can be in any order, but should be called - at the beginning. - #. only keyword arguments can be in any order, but should be called - at the end. - - Answer: only keyword arguments can be in any order, but should be called - at the end. - -#. Given the following function, identify the keywords with default - values. - :: - - def seperator(char, count=40, show=False): - - if show: - print char * count - - return char * count - - Answer: ``count``, ``show`` - -#. Given the following function, - :: - - def seperator(char, count=40, show=False): - - if show: - print char * count - - return char * count - - What is the output of ``separator("+", 1, True)``. - - Answer: ``+`` is printed and returned. - - -#. Given the following function, - :: - - def seperator(char, count=40, show=False): - - if show: - print char * count - - return char * count - - What is the output of ``separator("+", True, 1)``. - - Answer: ``+`` is printed and returned. - -#. Given the following function, - :: - - def seperator(char, count=40, show=False): - - if show: - print char * count - - return char * count - - What is the output of ``separator("+", show=True, 1)``. - - Answer: SyntaxError - -#. The following is a valid function definition. True or False? Why? - :: - - def seperator(count=40, char, show=False): - - if show: - print char * count - - return char * count - - Answer: False. All parameters with default arguments should be - defined at the end. - -#. Which of the following cannot be used as default values for - arguments? - - a. floats - #. lists - #. functions - #. booleans - #. None of the Above - - Answer: None of the above. - - -Larger Questions ----------------- - -1. - -2. diff -r 88a01948450d -r d33698326409 advanced-features-functions/quickref.tex --- a/advanced-features-functions/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,8 +0,0 @@ -\textbf{Advanced features of functions} - -Arguments of functions can have default arguments. - -All arguments with default arguments are at the end of the definition. - -Functions can be called with keyword arguments. All the keyword -arguments should be at the end of the argument list. diff -r 88a01948450d -r d33698326409 advanced-features-functions/script.rst --- a/advanced-features-functions/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,277 +0,0 @@ -.. Objectives -.. ---------- - -.. At the end of this tutorial, you will be able to - -.. 1. Assign default values to arguments, when defining functions -.. 2. Define and call functions with keyword arguments. -.. 3. Also, you will get a glimpse of the plethora of functions -.. available, in Python standard library and the scientific computing -.. libraries. - - -.. Prerequisites -.. ------------- - -.. 1. getting started with ipython -.. #. getting started with functions - -.. Author : Puneeth - Internal Reviewer : Anoop Jacob Thomas - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : [2010-10-05] - -Script ------- - -{{{ Show the slide containing title }}} - -Welcome to the tutorial on advanced feature of functions. - -{{{ Show the outline slide }}} - -In this tutorial we shall be looking at specifying default arguments -to functions when defining them and calling functions using keyword -arguments. We shall also, look at some of the built-in functions -available in the standard library of Python and the scientific -computing libraries. - -{{{ switch to terminal }}} - -We have an ``ipython`` terminal open, which we shall be using through -out this session. - -Let's use the ``round`` function as an example to understand what a -default value of an argument means. Let's type the following -expressions in the terminal. - -:: - - round(2.484) - - round(2.484, 2) - -Both the first expression and the second are calls to the ``round`` -function, but the first calls it with only one argument and the second -calls it with two arguments. By observing the output, we can guess -that the first one is equivalent to call with the second argument -being 0. 0 is the default value of the argument. - -.. #[[Anoop: It will be good if we show ``round??`` and tell them the - optional argument ndigits, or it could be given as an - exercise(solved) asking them to find the name of the argument in - the function round]] - -{{{ show a slide with examples of functions showing default values }}} - -.. #[[Anoop: I think the slide is not there]] - -:: - - s.strip() # strips on spaces. - s.strip('@') # strips the string of '@' symbols. - - plot(x, y) # plots with x vs. y using default line style. - plot(x, y, 'o') # plots x vs. y with circle markers. - - linspace(0, 2*pi, 100) # returns 100 points between 0 and 2pi - linspace(0, 2*pi) # returns 50 points between 0 and 2pi - -.. #[punch: all above content goes on to a slide] - -{{{ switch back to ipython }}} - -Let's now define a simple function that uses default arguments. We -define a simple function that prints a welcome message to a person, -given a greeting and his/her name. - -:: - - def welcome(greet, name="World"): - print greet, name - -Let us first call the function with two arguments, one for ``greet`` -and other for ``name``. - -:: - - welcome("Hi", "Guido") - -We get the expected welcome message, "Hi Guido". - -Now let us call the function with just one argument "Hello". -:: - - welcome("Hello") - -"Hello" is treated as the ``greet`` and we get "Hello World" as -the output. "World" is the default value for the argument ``name``. - -Following is an (are) exercise(s) that you must do. - -{{{ switch to next slide, containing problem statement of - question 1 }}} - -%%1%% Redefine the function ``welcome``, by interchanging it's -arguments. Place the ``name`` argument with it's default value of -"World" before the ``greet`` argument. - -Please, pause the video here. Do the exercise and then continue. - -{{{ switch to next slide, containing the solution to problem 1 }}} - -:: - - def welcome(name="World", greet): - print greet, name - -We get an error that reads ``SyntaxError: non-default argument follows -default argument``. When defining a function all the argument with -default values should come at the end. - -.. #[[Anoop: In the slide, "when defining a function all the default - arguments must be defined at the end" has to be emphasized"]] - -Following is an exercise that you must do. - -{{{ switch to next slide, containing the problem statement of - question 2 }}} - -%%2%% See the definition of linspace using ``?`` and observe how all -the arguments with default values are towards the end. - -Please, pause the video here. Do the exercise and then continue. - -{{{ switch to next slide, containing solution to problem 2 }}} - -:: - - linspace? - -Following is an exercise that you must do. - -{{{ switch to next slide, problem statement }}} - -%%3%% Redefine the function ``welcome`` with a default value of -"Hello" to the ``greet`` argument. Then, call the function without any -arguments. - -Please, pause the video here. Do the exercise and then continue. - -{{{ switch to next slide, solution }}} - -:: - - def welcome(greet="Hello", name="World"): - print greet, name - - - welcome() - - -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. }}} - -.. #[[Anoop: slide is missing]] - -:: - - legend(['sin(2y)'], loc = 'center') - - plot(y, sin(y), 'g', linewidth = 2) - - annotate('local max', xy = (1.5, 1)) - - pie(science.values(), labels = science.keys()) - -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 -function calls that use keyword arguments. ``loc``, ``linewidth``, -``xy`` and ``labels`` are being called with keyword arguments. - -{{{ switch to ipython terminal }}} - -Let us try and understand this better using the ``welcome`` function -that we have been using all along. Let us call it in different ways -and observe the output to see how keyword arguments work. - -:: - - welcome() - - welcome("Hello", "James") - - welcome("Hi", name="Guido") - -When no keyword is specified, the arguments are allotted based on -their position. So, "Hi" is the value of the argument ``greet`` and -name is passed the value "Guido". -:: - - welcome(name="Guido", greet="Hey! ") - -When keyword arguments are used, the arguments can be called in any -order. - -:: - - welcome(name="Guido", "Hey") - -This call returns an error that reads, ``non keyword arg after keyword -arg``. Python expects all the keyword to be present towards the end. - -That brings us to the end of what we wanted to learn about ``keyword`` -arguments. - -{{{ switch to a slide showing variety of functions with uses }}} - -.. #[[Anoop: slide missing]] - -Before defining a function of your own, make sure that you check the -standard library, for a similar function. Python is popularly called a -"Batteries included" language, for the huge library that comes along -with it. - -:: - - Math functions - abs, sin, .... - -.. #[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]] - -Apart from the standard library there are other libraries like ``pylab``, -``scipy``, etc which have a huge collection of functions for scientific -purposes. -:: - - pylab - plot, bar, contour, boxplot, errorbar, log, polar, quiver, semilog - - scipy (modules) - fftpack, stats, linalg, ndimage, signal, optimize, integrate - -{{{ Show summary slide }}} - -.. #[[Anoop: add range of functions available in python standard - library]] - -That brings us to the end of this tutorial. In this tutorial we have -learnt how to use functions with default values and keyword -arguments. We also looked at the range of functions available in the -Python standard library and the Scientific Computing related -packages. - -{{{ 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 88a01948450d -r d33698326409 advanced-features-functions/slides.org --- a/advanced-features-functions/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,86 +0,0 @@ -#+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: Advanced features of functions -#+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 - - Assigning default values to arguments - - Calling functions using Keyword arguments - - functions in standard library -* Question 1 - Redefine the function ~welcome~, by interchanging it's - arguments. Place the ~name~ argument with it's default value of - "World" before the ~greet~ argument. -* Solution 1 - #+begin_src python - def welcome(name="World", greet): - print greet, name - #+end_src - We get an error that reads ~SyntaxError: non-default argument - follows default argument~. When defining a function all the - argument with default values should come at the end. - -* Question 2 - See the definition of linspace using ~?~ and observe how all the - arguments with default values are towards the end. -* Solution 2 - #+begin_src python - linspace? - #+end_src -* Question 3 - Redefine the function ~welcome~ with a default value of - "Hello" to the ~greet~ argument. Then, call the function without any - arguments. -* Solution 3 - #+begin_src python - def welcome(greet="Hello", name="World"): - print greet, name - - welcome() - #+end_src -* Summary - You should now be able to -- - + define functions with default arguments - + call functions using keyword arguments -* 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 88a01948450d -r d33698326409 advanced-features-functions/slides.tex --- a/advanced-features-functions/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,134 +0,0 @@ -% Created 2010-10-28 Thu 11:37 -\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{Advanced features of 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 Assigning default values to arguments -\item Calling functions using Keyword arguments -\item functions in standard library -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Question 1} -\label{sec-2} - - Redefine the function \texttt{welcome}, by interchanging it's - arguments. Place the \texttt{name} argument with it's default value of - ``World'' before the \texttt{greet} argument. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 1} -\label{sec-3} - -\begin{verbatim} -def welcome(name="World", greet): - print greet, name -\end{verbatim} - We get an error that reads \texttt{SyntaxError: non-default argument follows default argument}. When defining a function all the - argument with default values should come at the end. -\end{frame} -\begin{frame} -\frametitle{Question 2} -\label{sec-4} - - See the definition of linspace using \texttt{?} and observe how all the - arguments with default values are towards the end. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 2} -\label{sec-5} - -\begin{verbatim} -linspace? -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Question 3} -\label{sec-6} - - Redefine the function \texttt{welcome} with a default value of - ``Hello'' to the \texttt{greet} argument. Then, call the function without any - arguments. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 3} -\label{sec-7} - -\begin{verbatim} -def welcome(greet="Hello", name="World"): - print greet, name - -welcome() -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-8} - - You should now be able to -- -\begin{itemize} -\item define functions with default arguments -\item call functions using keyword arguments -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-9} - - \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 88a01948450d -r d33698326409 advanced_features_of_functions/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/advanced_features_of_functions/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,109 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. All arguments of a function cannot have default values. True or + False? + + Answer: False + +#. When calling a function, the arguments + + 1. should always be in the order in which they are defined. + #. can be in any order + #. only keyword arguments can be in any order, but should be called + at the beginning. + #. only keyword arguments can be in any order, but should be called + at the end. + + Answer: only keyword arguments can be in any order, but should be called + at the end. + +#. Given the following function, identify the keywords with default + values. + :: + + def seperator(char, count=40, show=False): + + if show: + print char * count + + return char * count + + Answer: ``count``, ``show`` + +#. Given the following function, + :: + + def seperator(char, count=40, show=False): + + if show: + print char * count + + return char * count + + What is the output of ``separator("+", 1, True)``. + + Answer: ``+`` is printed and returned. + + +#. Given the following function, + :: + + def seperator(char, count=40, show=False): + + if show: + print char * count + + return char * count + + What is the output of ``separator("+", True, 1)``. + + Answer: ``+`` is printed and returned. + +#. Given the following function, + :: + + def seperator(char, count=40, show=False): + + if show: + print char * count + + return char * count + + What is the output of ``separator("+", show=True, 1)``. + + Answer: SyntaxError + +#. The following is a valid function definition. True or False? Why? + :: + + def seperator(count=40, char, show=False): + + if show: + print char * count + + return char * count + + Answer: False. All parameters with default arguments should be + defined at the end. + +#. Which of the following cannot be used as default values for + arguments? + + a. floats + #. lists + #. functions + #. booleans + #. None of the Above + + Answer: None of the above. + + +Larger Questions +---------------- + +1. + +2. diff -r 88a01948450d -r d33698326409 advanced_features_of_functions/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/advanced_features_of_functions/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,8 @@ +\textbf{Advanced features of functions} + +Arguments of functions can have default arguments. + +All arguments with default arguments are at the end of the definition. + +Functions can be called with keyword arguments. All the keyword +arguments should be at the end of the argument list. diff -r 88a01948450d -r d33698326409 advanced_features_of_functions/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/advanced_features_of_functions/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,277 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Assign default values to arguments, when defining functions +.. 2. Define and call functions with keyword arguments. +.. 3. Also, you will get a glimpse of the plethora of functions +.. available, in Python standard library and the scientific computing +.. libraries. + + +.. Prerequisites +.. ------------- + +.. 1. getting started with ipython +.. #. getting started with functions + +.. Author : Puneeth + Internal Reviewer : Anoop Jacob Thomas + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : [2010-10-05] + +Script +------ + +{{{ Show the slide containing title }}} + +Welcome to the tutorial on advanced feature of functions. + +{{{ Show the outline slide }}} + +In this tutorial we shall be looking at specifying default arguments +to functions when defining them and calling functions using keyword +arguments. We shall also, look at some of the built-in functions +available in the standard library of Python and the scientific +computing libraries. + +{{{ switch to terminal }}} + +We have an ``ipython`` terminal open, which we shall be using through +out this session. + +Let's use the ``round`` function as an example to understand what a +default value of an argument means. Let's type the following +expressions in the terminal. + +:: + + round(2.484) + + round(2.484, 2) + +Both the first expression and the second are calls to the ``round`` +function, but the first calls it with only one argument and the second +calls it with two arguments. By observing the output, we can guess +that the first one is equivalent to call with the second argument +being 0. 0 is the default value of the argument. + +.. #[[Anoop: It will be good if we show ``round??`` and tell them the + optional argument ndigits, or it could be given as an + exercise(solved) asking them to find the name of the argument in + the function round]] + +{{{ show a slide with examples of functions showing default values }}} + +.. #[[Anoop: I think the slide is not there]] + +:: + + s.strip() # strips on spaces. + s.strip('@') # strips the string of '@' symbols. + + plot(x, y) # plots with x vs. y using default line style. + plot(x, y, 'o') # plots x vs. y with circle markers. + + linspace(0, 2*pi, 100) # returns 100 points between 0 and 2pi + linspace(0, 2*pi) # returns 50 points between 0 and 2pi + +.. #[punch: all above content goes on to a slide] + +{{{ switch back to ipython }}} + +Let's now define a simple function that uses default arguments. We +define a simple function that prints a welcome message to a person, +given a greeting and his/her name. + +:: + + def welcome(greet, name="World"): + print greet, name + +Let us first call the function with two arguments, one for ``greet`` +and other for ``name``. + +:: + + welcome("Hi", "Guido") + +We get the expected welcome message, "Hi Guido". + +Now let us call the function with just one argument "Hello". +:: + + welcome("Hello") + +"Hello" is treated as the ``greet`` and we get "Hello World" as +the output. "World" is the default value for the argument ``name``. + +Following is an (are) exercise(s) that you must do. + +{{{ switch to next slide, containing problem statement of + question 1 }}} + +%%1%% Redefine the function ``welcome``, by interchanging it's +arguments. Place the ``name`` argument with it's default value of +"World" before the ``greet`` argument. + +Please, pause the video here. Do the exercise and then continue. + +{{{ switch to next slide, containing the solution to problem 1 }}} + +:: + + def welcome(name="World", greet): + print greet, name + +We get an error that reads ``SyntaxError: non-default argument follows +default argument``. When defining a function all the argument with +default values should come at the end. + +.. #[[Anoop: In the slide, "when defining a function all the default + arguments must be defined at the end" has to be emphasized"]] + +Following is an exercise that you must do. + +{{{ switch to next slide, containing the problem statement of + question 2 }}} + +%%2%% See the definition of linspace using ``?`` and observe how all +the arguments with default values are towards the end. + +Please, pause the video here. Do the exercise and then continue. + +{{{ switch to next slide, containing solution to problem 2 }}} + +:: + + linspace? + +Following is an exercise that you must do. + +{{{ switch to next slide, problem statement }}} + +%%3%% Redefine the function ``welcome`` with a default value of +"Hello" to the ``greet`` argument. Then, call the function without any +arguments. + +Please, pause the video here. Do the exercise and then continue. + +{{{ switch to next slide, solution }}} + +:: + + def welcome(greet="Hello", name="World"): + print greet, name + + + welcome() + + +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. }}} + +.. #[[Anoop: slide is missing]] + +:: + + legend(['sin(2y)'], loc = 'center') + + plot(y, sin(y), 'g', linewidth = 2) + + annotate('local max', xy = (1.5, 1)) + + pie(science.values(), labels = science.keys()) + +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 +function calls that use keyword arguments. ``loc``, ``linewidth``, +``xy`` and ``labels`` are being called with keyword arguments. + +{{{ switch to ipython terminal }}} + +Let us try and understand this better using the ``welcome`` function +that we have been using all along. Let us call it in different ways +and observe the output to see how keyword arguments work. + +:: + + welcome() + + welcome("Hello", "James") + + welcome("Hi", name="Guido") + +When no keyword is specified, the arguments are allotted based on +their position. So, "Hi" is the value of the argument ``greet`` and +name is passed the value "Guido". +:: + + welcome(name="Guido", greet="Hey! ") + +When keyword arguments are used, the arguments can be called in any +order. + +:: + + welcome(name="Guido", "Hey") + +This call returns an error that reads, ``non keyword arg after keyword +arg``. Python expects all the keyword to be present towards the end. + +That brings us to the end of what we wanted to learn about ``keyword`` +arguments. + +{{{ switch to a slide showing variety of functions with uses }}} + +.. #[[Anoop: slide missing]] + +Before defining a function of your own, make sure that you check the +standard library, for a similar function. Python is popularly called a +"Batteries included" language, for the huge library that comes along +with it. + +:: + + Math functions - abs, sin, .... + +.. #[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]] + +Apart from the standard library there are other libraries like ``pylab``, +``scipy``, etc which have a huge collection of functions for scientific +purposes. +:: + + pylab + plot, bar, contour, boxplot, errorbar, log, polar, quiver, semilog + + scipy (modules) + fftpack, stats, linalg, ndimage, signal, optimize, integrate + +{{{ Show summary slide }}} + +.. #[[Anoop: add range of functions available in python standard + library]] + +That brings us to the end of this tutorial. In this tutorial we have +learnt how to use functions with default values and keyword +arguments. We also looked at the range of functions available in the +Python standard library and the Scientific Computing related +packages. + +{{{ 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 88a01948450d -r d33698326409 advanced_features_of_functions/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/advanced_features_of_functions/slides.org Wed Dec 01 16:51:35 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{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Advanced features of functions +#+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 + - Assigning default values to arguments + - Calling functions using Keyword arguments + - functions in standard library +* Question 1 + Redefine the function ~welcome~, by interchanging it's + arguments. Place the ~name~ argument with it's default value of + "World" before the ~greet~ argument. +* Solution 1 + #+begin_src python + def welcome(name="World", greet): + print greet, name + #+end_src + We get an error that reads ~SyntaxError: non-default argument + follows default argument~. When defining a function all the + argument with default values should come at the end. + +* Question 2 + See the definition of linspace using ~?~ and observe how all the + arguments with default values are towards the end. +* Solution 2 + #+begin_src python + linspace? + #+end_src +* Question 3 + Redefine the function ~welcome~ with a default value of + "Hello" to the ~greet~ argument. Then, call the function without any + arguments. +* Solution 3 + #+begin_src python + def welcome(greet="Hello", name="World"): + print greet, name + + welcome() + #+end_src +* Summary + You should now be able to -- + + define functions with default arguments + + call functions using keyword arguments +* 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 88a01948450d -r d33698326409 advanced_features_of_functions/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/advanced_features_of_functions/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,134 @@ +% Created 2010-10-28 Thu 11:37 +\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{Advanced features of 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 Assigning default values to arguments +\item Calling functions using Keyword arguments +\item functions in standard library +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Redefine the function \texttt{welcome}, by interchanging it's + arguments. Place the \texttt{name} argument with it's default value of + ``World'' before the \texttt{greet} argument. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-3} + +\begin{verbatim} +def welcome(name="World", greet): + print greet, name +\end{verbatim} + We get an error that reads \texttt{SyntaxError: non-default argument follows default argument}. When defining a function all the + argument with default values should come at the end. +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + See the definition of linspace using \texttt{?} and observe how all the + arguments with default values are towards the end. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} + +\begin{verbatim} +linspace? +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + + Redefine the function \texttt{welcome} with a default value of + ``Hello'' to the \texttt{greet} argument. Then, call the function without any + arguments. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 3} +\label{sec-7} + +\begin{verbatim} +def welcome(greet="Hello", name="World"): + print greet, name + +welcome() +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-8} + + You should now be able to -- +\begin{itemize} +\item define functions with default arguments +\item call functions using keyword arguments +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-9} + + \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 88a01948450d -r d33698326409 basic-data-type/questions.rst --- a/basic-data-type/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -.. #[Puneeth: ``Answer: Any size.``. Demarcate the answer from the -.. question.] - -1. How large can an integer in Python be? - - Answer: Any Size. - - -#. How do you define a complex number in Python? - - Using the following notation. - - [Real part] + [Imaginary part] j - example :: - - Answer: c= 3.2 + 4.6j - - -#. 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 ? - -#. One major diffence between tuples and lists? - - Answer: Tuples are immutable while lists are not. - - - - -#. 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 - - What might be the reason for error here? - - In this scenario , it seems the programmer wanted to create a - variable t with the boolean value True with a capital T. Since no - variable by the name true(small t) is known to the interpreter it - gives a NameError. - - - -#. 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 88a01948450d -r d33698326409 basic-data-type/quickref.tex --- a/basic-data-type/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,49 +0,0 @@ -\documentclass{article} -\begin{Document} -\begin{center} -\textbf{Basic DataType Quick Reference}\\ -\end{center} -Declaring an Integer:\\ -{\ex \lstinline| b=9999999999999999999 |} - -Declaring a float:\\ -{\ex \lstinline| p=3.141592 |} - -Declaring a Complex number:\\ -{\ex \lstinline| c = 3.2+4.6j |} - -Modulo Operator:\\ -{\ex \lstinline| 87 % 6 |} - -Exponent Operator:\\ -{\ex \lstinline| 7**8 |} - -Declaring a list:\\ -{\ex \lstinline| var_list = [1, 1.2, [1,2]] |} - -Declaring a string:\\ -{\ex \lstinline| k='Single quote' |} -{\ex \lstinline| l="Double quote contain's single quote" |} -{\ex \lstinline| m='''"Contain's both"''' |} - -Declaring a tuple:\\ -{\ex \lstinline| var_tup = (1,2,3,4) |} - - -Accessing Lists, string and tuples:\\ -{\ex \lstinline| seq[-1] |} - -Interconversion of number datatype:\\ -{\ex \lstinline| float(2.3+4.2j) |} - - -Interconversion of sequences:\\ -{\ex \lstinline| tup=tuple([1,2,3,4,5]) |} - -Spliting string into lists:\\ -{\ex \lstinline| ''split this sting''.split() |} - -Join lists to create strings:\\ -{\ex \lstinline| ','.join['List','joined','on','commas'] |} - -\end{Document} diff -r 88a01948450d -r d33698326409 basic-data-type/script.rst --- a/basic-data-type/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,553 +0,0 @@ -.. Objectives -.. ---------- - -.. At the end of this tutorial, you should know -- - -.. 1. Learn about Python Data Structures and Operators.(Remembering) -.. #.Use them to do basic operations.(Applying) - -.. Prerequisites -.. ------------- - -.. None - -.. Author : Amit Sethi - Internal Reviewer : - External Reviewer : - Checklist OK? : [2010-10-05] - -Hello friends and welcome to the tutorial on Basic Data types and operators -in Python. - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall look at - -* Datatypes in Python - * Numbers - * Boolean - * Sequence -* Operators in Python - * Arithmetic Operators - * Boolean Operators - -* 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 the different datatypes }}} - -These are: - - * int - * float - * complex - -Lets first talk about int. :: - - a = 13 - a - - -Now, we have our first int variable a. - - -If we now see :: - - type(a) - - -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. - -*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. This is because python's int data-type can hold integers of any -size. - -Let us now look at the float data-type. - -Decimal numbers in python are represented by the float data-type :: - - 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 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 :: - - c = 3.2+4.6j - -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. Let us look at these :: - - c. - -Lets try some of them :: - - c.real - c.imag - -c.real gives the real part of the number and c.imag the imaginary. - -We can get the absolute value using the function :: - - abs(c) - - -Following is are exercises that you must do. - -%% %% 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. - -Try it out just type :: - - t = True - -note that T in true is capitalized. - -You can apply different Boolean operations on t now for example :: - - f = not t - f - f or t - f and t - - -The results are self explanatory. - -What if you want to apply one operator before another. - -Well you can use parenthesis for precedence. - -Lets write some piece of code to check this out.:: - - a=False - b=True - c=True - - -To check how precedence changes with parenthesis, we will try two -expressions and their evaluation. - -one :: - - (a and b) or c - -This expression gives the value True - -where as the expression :: - - a and (b or c) - -gives the value False. - - -Let's now look at some operators available in Python to manipulate -these data types. - -Python uses '+' for addition :: - - 23 + 74 - -'-' for subtraction :: - - 23 - 56 - -'*' for multiplication :: - - 45*76 - -'/' for division :: - - 384/16 - 8/3 - 8.0/3 - -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 - -and two stars for a exponent. :: - - 7**8 - - -In case one wishes to use the current value of variable in which the result -is stored in the expression one can do that by putting the operator before -`equal to`. :: - - a=73 - a*=34 - -is same as :: - - a=a*34 - -and :: - - a/=23 - -is same as :: - - 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 are accessed using index numbers. - -{{{ slide introducing sequence datatype }}} - -The sequence datatypes in Python are :: - - * list - * string - * tuple - -The list type is a container that holds a number of other objects, in the -given order. - -We create our first list by typing :: - - num_list = [1, 2, 3, 4] - num_list - - -Items enclosed in square brackets separated by comma constitutes a list. - -Lists can store data of any type in them. - -We can have a list something like :: - - var_list = [1, 1.2, [1,2]] - var_list - -Lets look at another sequence data type, strings - -type :: - - greeting_string="hello" - - -greeting_string is now a string variable with the value "hello" - -{{{ All the different types of strings shown }}} - -Python strings can actually be defined in three different ways :: - - k='Single quote' - l="Let's see how to include a single quote" - m='''"Let's see how to include both"''' - -As you can see, single quotes are used as delimiters usually. - -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. - -The last in the list of sequence data types is tuple. - -To create a tuple we use normal brackets '(' unlike '[' for lists.:: - - num_tuple = (1, 2, 3, 4, 5, 6, 7, 8) - -Because of their sequential property there are certain functions and -operations we can apply to all of them. - - - -The first one is accessing. - -They can be accessed using index numbers :: - - num_list[2] - num_list[-1] - greeting_string[1] - greeting_string[3] - greeting_string[-2] - num_tuple[2] - num_tuple[-3] - - -Indexing starts from 0 from left to right and from -1 when accessing lists -in reverse. Thus num_list[2] refers to the third element 3. and greetings -[-2] is the second element from the end , that is 'l'. - - - -Addition gives a new sequence containing both sequences :: - - num_list+var_list - a_string="another string" - greeting_string+a_string - t2=(3,4,6,7) - num_tuple+t2 - -len function gives the length :: - - len(num_list) - len(greeting_string) - len(num_tuple) - -Prints the length the variable. - -We can check the containership of an element using the 'in' keyword :: - - 3 in num_list - 'H' in greeting_string - 2 in num_tuple - -We see that it gives True and False accordingly. - -Find maximum using max function and minimum using min:: - - max(num_tuple) - min(greeting_string) - -Get a sorted list :: - - sorted(num_list) - - -As a consequence of their order, we can access a group of elements in a -sequence, together. This is called slicing and striding. - -First lets discuss Slicing, - -Given a list :: - - j=[1,2,3,4,5,6] - -Lets say we want elements starting from 2 and ending in 5. - -For this we can do :: - - j[1:4] - -The syntax for slicing is, sequence variable name square bracket first -element index, colon, second element index. The last element however is not -included in the resultant list:: - - - j[:4] - -If first element is left blank default is from beginning and if last -element is left blank it means till the end. - -:: - - j[1:] - - j[:] - -This effectively is the whole list. - -Striding is similar to slicing except that the step size here is not one. - -Lets see by example :: - - new_num_list=[1,2,3,4,5,6,7,8,9,10] - new_num_list[1:8:2] - [2, 4, 6, 8] - -The colon two added in the end signifies all the alternate elements. This -is why we call this concept striding because we move through the list with -a particular stride or step. The step in this example being 2. - -We have talked about many similar features of lists, strings and tuples. -But there are many important features in lists that differ from strings and -tuples. Lets see this by example.:: - - new_num_list[1]=9 - greeting_string[1]='k' - -{{{ slide to show the error }}} - - - -As you can see while the first command executes with out a problem there is -an error on the second one. - -Now lets try :: - - new_tuple[1]=5 - -Its the same error. This is because strings and tuples share the property -of being immutable. We cannot change the value at a particular index just -by assigning a new value at that position. - - -We have looked at different types but we need to convert one data type into -another. Well lets one by one go through methods by which we can convert -one data type to other: - -We can convert all the number data types to one another :: - - i=34 - d=float(i) - d - -Python has built in functions int, float and complex to convert one number -type data structure to another. - -:: - - dec=2.34 - dec_con=int(dec) - dec_con - - -As you can see the decimal part of the number is simply stripped to get the -integer.:: - - com=2.3+4.2j - float(com) - com - -In case of complex number to floating point only the real value of complex -number is taken. - -Similarly we can convert list to tuple and tuple to list :: - - lst=[3,4,5,6] - tup=tuple(lst) - tupl=(3,23,4,56) - lst=list(tuple) - -However converting a string to a list and a list to a string is an -interesting problem. Let's say we have a string :: - - In: somestring="Is there a way to split on these spaces." - In: somestring.split() - - -This produces a list with the string split at whitespace. Similarly we can -split on some other character. - -:: - - In: otherstring="Tim,Amy,Stewy,Boss" - -How do we split on comma , simply pass it as argument :: - - In: otherstring.split(',') - -join function does the opposite. Joins a list to make a string.:: - - ','.join['List','joined','on','commas'] - -Thus we get a list joined on commas. Similarly we can do spaces.:: - - ' '.join['Now','on','spaces'] - -Note that the list has to be a list of strings to apply join operation. - -With this we come to the end of this tutorial . - -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 -3. Sequence data types ,List,String and Tuple -4. Accesing sequence -5. Slicing sequences -6. Finding length , sorting and reversing operations on sequences. -7. Immutability. - -{{{ 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. - - -.. - Local Variables: - mode: rst - indent-tabs-mode: nil - sentence-end-double-space: nil - fill-column: 75 - End: diff -r 88a01948450d -r d33698326409 basic-data-type/slides.org --- a/basic-data-type/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,158 +0,0 @@ -#+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 88a01948450d -r d33698326409 basic-data-type/slides.org.orig --- a/basic-data-type/slides.org.orig Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,158 +0,0 @@ -#+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 88a01948450d -r d33698326409 basic-data-type/slides.tex --- a/basic-data-type/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,286 +0,0 @@ -% Created 2010-11-09 Tue 15:26 -\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{Plotting Data } -\author{FOSSEE} -\date{2010-09-14 Tue} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} -\begin{itemize} - -\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} - -\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-7} - -\begin{verbatim} -In []: t=True -In []: f=False -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Question 3} -\label{sec-8} - -\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-12} -\begin{itemize} - -\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{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{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} - -\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-19} - -\begin{itemize} -\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{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 88a01948450d -r d33698326409 basic_datatypes_and_operators/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic_datatypes_and_operators/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,94 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +.. #[Puneeth: ``Answer: Any size.``. Demarcate the answer from the +.. question.] + +1. How large can an integer in Python be? + + Answer: Any Size. + + +#. How do you define a complex number in Python? + + Using the following notation. + + [Real part] + [Imaginary part] j + example :: + + Answer: c= 3.2 + 4.6j + + +#. 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 ? + +#. One major diffence between tuples and lists? + + Answer: Tuples are immutable while lists are not. + + + + +#. 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 + + What might be the reason for error here? + + In this scenario , it seems the programmer wanted to create a + variable t with the boolean value True with a capital T. Since no + variable by the name true(small t) is known to the interpreter it + gives a NameError. + + + +#. 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 88a01948450d -r d33698326409 basic_datatypes_and_operators/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic_datatypes_and_operators/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,49 @@ +\documentclass{article} +\begin{Document} +\begin{center} +\textbf{Basic DataType Quick Reference}\\ +\end{center} +Declaring an Integer:\\ +{\ex \lstinline| b=9999999999999999999 |} + +Declaring a float:\\ +{\ex \lstinline| p=3.141592 |} + +Declaring a Complex number:\\ +{\ex \lstinline| c = 3.2+4.6j |} + +Modulo Operator:\\ +{\ex \lstinline| 87 % 6 |} + +Exponent Operator:\\ +{\ex \lstinline| 7**8 |} + +Declaring a list:\\ +{\ex \lstinline| var_list = [1, 1.2, [1,2]] |} + +Declaring a string:\\ +{\ex \lstinline| k='Single quote' |} +{\ex \lstinline| l="Double quote contain's single quote" |} +{\ex \lstinline| m='''"Contain's both"''' |} + +Declaring a tuple:\\ +{\ex \lstinline| var_tup = (1,2,3,4) |} + + +Accessing Lists, string and tuples:\\ +{\ex \lstinline| seq[-1] |} + +Interconversion of number datatype:\\ +{\ex \lstinline| float(2.3+4.2j) |} + + +Interconversion of sequences:\\ +{\ex \lstinline| tup=tuple([1,2,3,4,5]) |} + +Spliting string into lists:\\ +{\ex \lstinline| ''split this sting''.split() |} + +Join lists to create strings:\\ +{\ex \lstinline| ','.join['List','joined','on','commas'] |} + +\end{Document} diff -r 88a01948450d -r d33698326409 basic_datatypes_and_operators/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic_datatypes_and_operators/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,553 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you should know -- + +.. 1. Learn about Python Data Structures and Operators.(Remembering) +.. #.Use them to do basic operations.(Applying) + +.. Prerequisites +.. ------------- + +.. None + +.. Author : Amit Sethi + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Hello friends and welcome to the tutorial on Basic Data types and operators +in Python. + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall look at + +* Datatypes in Python + * Numbers + * Boolean + * Sequence +* Operators in Python + * Arithmetic Operators + * Boolean Operators + +* 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 the different datatypes }}} + +These are: + + * int + * float + * complex + +Lets first talk about int. :: + + a = 13 + a + + +Now, we have our first int variable a. + + +If we now see :: + + type(a) + + +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. + +*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. This is because python's int data-type can hold integers of any +size. + +Let us now look at the float data-type. + +Decimal numbers in python are represented by the float data-type :: + + 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 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 :: + + c = 3.2+4.6j + +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. Let us look at these :: + + c. + +Lets try some of them :: + + c.real + c.imag + +c.real gives the real part of the number and c.imag the imaginary. + +We can get the absolute value using the function :: + + abs(c) + + +Following is are exercises that you must do. + +%% %% 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. + +Try it out just type :: + + t = True + +note that T in true is capitalized. + +You can apply different Boolean operations on t now for example :: + + f = not t + f + f or t + f and t + + +The results are self explanatory. + +What if you want to apply one operator before another. + +Well you can use parenthesis for precedence. + +Lets write some piece of code to check this out.:: + + a=False + b=True + c=True + + +To check how precedence changes with parenthesis, we will try two +expressions and their evaluation. + +one :: + + (a and b) or c + +This expression gives the value True + +where as the expression :: + + a and (b or c) + +gives the value False. + + +Let's now look at some operators available in Python to manipulate +these data types. + +Python uses '+' for addition :: + + 23 + 74 + +'-' for subtraction :: + + 23 - 56 + +'*' for multiplication :: + + 45*76 + +'/' for division :: + + 384/16 + 8/3 + 8.0/3 + +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 + +and two stars for a exponent. :: + + 7**8 + + +In case one wishes to use the current value of variable in which the result +is stored in the expression one can do that by putting the operator before +`equal to`. :: + + a=73 + a*=34 + +is same as :: + + a=a*34 + +and :: + + a/=23 + +is same as :: + + 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 are accessed using index numbers. + +{{{ slide introducing sequence datatype }}} + +The sequence datatypes in Python are :: + + * list + * string + * tuple + +The list type is a container that holds a number of other objects, in the +given order. + +We create our first list by typing :: + + num_list = [1, 2, 3, 4] + num_list + + +Items enclosed in square brackets separated by comma constitutes a list. + +Lists can store data of any type in them. + +We can have a list something like :: + + var_list = [1, 1.2, [1,2]] + var_list + +Lets look at another sequence data type, strings + +type :: + + greeting_string="hello" + + +greeting_string is now a string variable with the value "hello" + +{{{ All the different types of strings shown }}} + +Python strings can actually be defined in three different ways :: + + k='Single quote' + l="Let's see how to include a single quote" + m='''"Let's see how to include both"''' + +As you can see, single quotes are used as delimiters usually. + +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. + +The last in the list of sequence data types is tuple. + +To create a tuple we use normal brackets '(' unlike '[' for lists.:: + + num_tuple = (1, 2, 3, 4, 5, 6, 7, 8) + +Because of their sequential property there are certain functions and +operations we can apply to all of them. + + + +The first one is accessing. + +They can be accessed using index numbers :: + + num_list[2] + num_list[-1] + greeting_string[1] + greeting_string[3] + greeting_string[-2] + num_tuple[2] + num_tuple[-3] + + +Indexing starts from 0 from left to right and from -1 when accessing lists +in reverse. Thus num_list[2] refers to the third element 3. and greetings +[-2] is the second element from the end , that is 'l'. + + + +Addition gives a new sequence containing both sequences :: + + num_list+var_list + a_string="another string" + greeting_string+a_string + t2=(3,4,6,7) + num_tuple+t2 + +len function gives the length :: + + len(num_list) + len(greeting_string) + len(num_tuple) + +Prints the length the variable. + +We can check the containership of an element using the 'in' keyword :: + + 3 in num_list + 'H' in greeting_string + 2 in num_tuple + +We see that it gives True and False accordingly. + +Find maximum using max function and minimum using min:: + + max(num_tuple) + min(greeting_string) + +Get a sorted list :: + + sorted(num_list) + + +As a consequence of their order, we can access a group of elements in a +sequence, together. This is called slicing and striding. + +First lets discuss Slicing, + +Given a list :: + + j=[1,2,3,4,5,6] + +Lets say we want elements starting from 2 and ending in 5. + +For this we can do :: + + j[1:4] + +The syntax for slicing is, sequence variable name square bracket first +element index, colon, second element index. The last element however is not +included in the resultant list:: + + + j[:4] + +If first element is left blank default is from beginning and if last +element is left blank it means till the end. + +:: + + j[1:] + + j[:] + +This effectively is the whole list. + +Striding is similar to slicing except that the step size here is not one. + +Lets see by example :: + + new_num_list=[1,2,3,4,5,6,7,8,9,10] + new_num_list[1:8:2] + [2, 4, 6, 8] + +The colon two added in the end signifies all the alternate elements. This +is why we call this concept striding because we move through the list with +a particular stride or step. The step in this example being 2. + +We have talked about many similar features of lists, strings and tuples. +But there are many important features in lists that differ from strings and +tuples. Lets see this by example.:: + + new_num_list[1]=9 + greeting_string[1]='k' + +{{{ slide to show the error }}} + + + +As you can see while the first command executes with out a problem there is +an error on the second one. + +Now lets try :: + + new_tuple[1]=5 + +Its the same error. This is because strings and tuples share the property +of being immutable. We cannot change the value at a particular index just +by assigning a new value at that position. + + +We have looked at different types but we need to convert one data type into +another. Well lets one by one go through methods by which we can convert +one data type to other: + +We can convert all the number data types to one another :: + + i=34 + d=float(i) + d + +Python has built in functions int, float and complex to convert one number +type data structure to another. + +:: + + dec=2.34 + dec_con=int(dec) + dec_con + + +As you can see the decimal part of the number is simply stripped to get the +integer.:: + + com=2.3+4.2j + float(com) + com + +In case of complex number to floating point only the real value of complex +number is taken. + +Similarly we can convert list to tuple and tuple to list :: + + lst=[3,4,5,6] + tup=tuple(lst) + tupl=(3,23,4,56) + lst=list(tuple) + +However converting a string to a list and a list to a string is an +interesting problem. Let's say we have a string :: + + In: somestring="Is there a way to split on these spaces." + In: somestring.split() + + +This produces a list with the string split at whitespace. Similarly we can +split on some other character. + +:: + + In: otherstring="Tim,Amy,Stewy,Boss" + +How do we split on comma , simply pass it as argument :: + + In: otherstring.split(',') + +join function does the opposite. Joins a list to make a string.:: + + ','.join['List','joined','on','commas'] + +Thus we get a list joined on commas. Similarly we can do spaces.:: + + ' '.join['Now','on','spaces'] + +Note that the list has to be a list of strings to apply join operation. + +With this we come to the end of this tutorial . + +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 +3. Sequence data types ,List,String and Tuple +4. Accesing sequence +5. Slicing sequences +6. Finding length , sorting and reversing operations on sequences. +7. Immutability. + +{{{ 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. + + +.. + Local Variables: + mode: rst + indent-tabs-mode: nil + sentence-end-double-space: nil + fill-column: 75 + End: diff -r 88a01948450d -r d33698326409 basic_datatypes_and_operators/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic_datatypes_and_operators/slides.org Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 basic_datatypes_and_operators/slides.org.orig --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic_datatypes_and_operators/slides.org.orig Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 basic_datatypes_and_operators/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic_datatypes_and_operators/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,286 @@ +% Created 2010-11-09 Tue 15:26 +\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{Plotting Data } +\author{FOSSEE} +\date{2010-09-14 Tue} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} +\begin{itemize} + +\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} + +\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-7} + +\begin{verbatim} +In []: t=True +In []: f=False +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-8} + +\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-12} +\begin{itemize} + +\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{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{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} + +\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-19} + +\begin{itemize} +\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{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 88a01948450d -r d33698326409 getting-started-files/pendulum.txt --- a/getting-started-files/pendulum.txt Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,90 +0,0 @@ -1.0000e-01 6.9004e-01 -1.1000e-01 6.9497e-01 -1.2000e-01 7.4252e-01 -1.3000e-01 7.5360e-01 -1.4000e-01 8.3568e-01 -1.5000e-01 8.6789e-01 -1.6000e-01 8.4182e-01 -1.7000e-01 8.5379e-01 -1.8000e-01 8.5762e-01 -1.9000e-01 8.8390e-01 -2.0000e-01 8.9985e-01 -2.1000e-01 9.8436e-01 -2.2000e-01 1.0244e+00 -2.3000e-01 1.0572e+00 -2.4000e-01 9.9077e-01 -2.5000e-01 1.0058e+00 -2.6000e-01 1.0727e+00 -2.7000e-01 1.0943e+00 -2.8000e-01 1.1432e+00 -2.9000e-01 1.1045e+00 -3.0000e-01 1.1867e+00 -3.1000e-01 1.1385e+00 -3.2000e-01 1.2245e+00 -3.3000e-01 1.2406e+00 -3.4000e-01 1.2071e+00 -3.5000e-01 1.2658e+00 -3.6000e-01 1.2995e+00 -3.7000e-01 1.3142e+00 -3.8000e-01 1.2663e+00 -3.9000e-01 1.2578e+00 -4.0000e-01 1.2991e+00 -4.1000e-01 1.3058e+00 -4.2000e-01 1.3478e+00 -4.3000e-01 1.3506e+00 -4.4000e-01 1.4044e+00 -4.5000e-01 1.3948e+00 -4.6000e-01 1.3800e+00 -4.7000e-01 1.4480e+00 -4.8000e-01 1.4168e+00 -4.9000e-01 1.4719e+00 -5.0000e-01 1.4656e+00 -5.1000e-01 1.4399e+00 -5.2000e-01 1.5174e+00 -5.3000e-01 1.4988e+00 -5.4000e-01 1.4751e+00 -5.5000e-01 1.5326e+00 -5.6000e-01 1.5297e+00 -5.7000e-01 1.5372e+00 -5.8000e-01 1.6094e+00 -5.9000e-01 1.6352e+00 -6.0000e-01 1.5843e+00 -6.1000e-01 1.6643e+00 -6.2000e-01 1.5987e+00 -6.3000e-01 1.6585e+00 -6.4000e-01 1.6317e+00 -6.5000e-01 1.7074e+00 -6.6000e-01 1.6654e+00 -6.7000e-01 1.6551e+00 -6.8000e-01 1.6964e+00 -6.9000e-01 1.7143e+00 -7.0000e-01 1.7706e+00 -7.1000e-01 1.7622e+00 -7.2000e-01 1.7260e+00 -7.3000e-01 1.8089e+00 -7.4000e-01 1.7905e+00 -7.5000e-01 1.7428e+00 -7.6000e-01 1.8381e+00 -7.7000e-01 1.8182e+00 -7.8000e-01 1.7865e+00 -7.9000e-01 1.7995e+00 -8.0000e-01 1.8296e+00 -8.1000e-01 1.8625e+00 -8.2000e-01 1.8623e+00 -8.3000e-01 1.8383e+00 -8.4000e-01 1.8593e+00 -8.5000e-01 1.8944e+00 -8.6000e-01 1.9598e+00 -8.7000e-01 1.9000e+00 -8.8000e-01 1.9244e+00 -8.9000e-01 1.9397e+00 -9.0000e-01 1.9440e+00 -9.1000e-01 1.9718e+00 -9.2000e-01 1.9383e+00 -9.3000e-01 1.9555e+00 -9.4000e-01 2.0006e+00 -9.5000e-01 1.9841e+00 -9.6000e-01 2.0066e+00 -9.7000e-01 2.0493e+00 -9.8000e-01 2.0503e+00 -9.9000e-01 2.0214e+00 diff -r 88a01948450d -r d33698326409 getting-started-files/questions.rst --- a/getting-started-files/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,136 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here. - -1. What function is used to open a file? - - Answer: ``open`` - -#. The ``open`` function returns a - - a. string - #. list - #. file object - #. function - - Answer: file object - -#. ``open`` function opens a file by default in write mode. T or F? - - Answer: False - -#. The ``read`` method reads a file and returns the contents - - a. string - #. list - #. file object - #. None of the above - - Answer: string - -#. Given a file with ``hello.txt``, which looks like - :: - - Hello, World! - - What is the value of content, at the end of this code block:: - - f = open('hello.txt') - pre_content = f.read() - content = f.read() - f.close() - - Answer: It is a null string. - -#. The following code block prints each line of ``hello.txt``:: - - f = open('hello.txt') - for line in f.read(): - print line - - True or False? - - Answer: False - -#. Given a file with ``hello.txt``, which looks like - :: - - Hello, World! - - What is the output of :: - - f = open('hello.txt') - - for line in f: - print line - - for line in f: - print line - - f.close() - - Answer: Hello, World! is printed once. - - .. The actual answer should talk about blank lines, but I'm - .. not sure if we should get into such detail. - - .. Should this be made a multiple-choice? - - .. #[[Anoop: I think it will better if we make this multiple - choice]] - -#. Given a file with ``hello.txt``, which looks like - :: - - Hello, World! - - What is the output of :: - - f = open('hello.txt') - - for line in f: - print line - - f.close() - - for line in f: - print line - - f.close() - - Answer: Hello, World! is printed twice. - -#. Given a file with ``hello.txt``, which looks like - :: - - Hello, World! - - What is the output of :: - - f = open('hello') - - for line in f: - print line - - f.close() - - for line in f: - print line - - f.close() - - Answer: IOError - No such file or directory: 'hello' - - -Larger Questions ----------------- - -.. A minimum of 2 questions here. - -1. What does ``f.read(size)`` do? - -#. Print every alternate line of a file, starting at the first line. - -#. Print the file in reverse. Starting from the last line to the - first. diff -r 88a01948450d -r d33698326409 getting-started-files/quickref.tex --- a/getting-started-files/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,12 +0,0 @@ -\textbf{Getting Started -- files} - -\lstinline|f = open('filename')| returns a file object. \lstinline|f| -can be used to perform further operations on the file. - -\lstinline|f.read()| reads the whole file and returns the contents. - -\lstinline|f.close()| closes the file. - -\lstinline|for line in open('filename'):| -- iterate over the file -line-by-line. - diff -r 88a01948450d -r d33698326409 getting-started-files/script.rst --- a/getting-started-files/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,189 +0,0 @@ -.. Objectives -.. ---------- - -.. By the end of this tutorial, you will be able to -.. 1. Open and read the contents of a file. -.. #. Read files line by line. -.. #. Read all the contents of the file at once. -.. #. Close open files. - -.. Prerequisites -.. ------------- - -.. 1. getting started with ipython -.. #. getting started with lists -.. #. getting started with for - -.. Author : Puneeth - Internal Reviewer : Anoop Jacob Thomas - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <06-11-2010, Anand, OK> [2010-10-05] - -Script ------- - -{{{ Show the slide containing title }}} - -Hello Friends. Welcome to the tutorial on getting started with files. - -{{{ Show the outline for this tutorial }}} - -In this tutorial we shall learn to read files, and do some basic -actions on the file, like opening and reading a file, closing a -file, iterating through the file line-by-line, and appending the -lines of a file to a list. - -{{{ switch back to the terminal }}} - -As usual, we start IPython, using -:: - - ipython -pylab - -Let us first open the file, ``pendulum.txt`` present in -``/home/fossee/``. -:: - - f = open('/home/fossee/pendulum.txt') - -``f`` is called a file object. Let us type ``f`` on the terminal to -see what it is. -:: - - f - -The file object shows, the file which is open and the mode (read -or write) in which it is open. Notice that it is open in read only -mode, here. - -We shall first learn to read the whole file into a single -variable. Later, we shall look at reading it line-by-line. We use -the ``read`` method of ``f`` to read, all the contents of the file -into the variable ``pend``. -:: - - pend = f.read() - -Now, let us see what is in ``pend``, by typing -:: - - print pend - -We can see that ``pend`` has all the data of the file. Type just ``pend`` -to see more explicitly, what it contains. -:: - - pend - -Following is an exercise that you must do. - -{{ show slide with Question 1 }} - -%%1%% Split the variable into a list, ``pend_list``, of the lines in -the file. Hint, use the tab command to see what methods the string -variable has. - -Please, pause the video here. Do the exercise and then continue. - -{{ show slide with Solution 1 }} - -:: - - pend_list = pend.splitlines() - - pend_list - -Now, let us learn to read the file line-by-line. But, before that we -will have to close the file, since the file has already been read till -the end. - -Let us close the file opened into f. -:: - - f.close() - -Let us again type ``f`` on the prompt to see what it shows. -:: - - f - -Notice, that it now says the file has been closed. It is a good -programming practice to close any file objects that we have -opened, after their job is done. - -Let us, now move on to reading files line-by-line. - -Following is an exercise that you must do. - -%%2%% Re-open the file ``pendulum.txt`` with ``f`` as the file object. - -Please, pause the video here. Do the exercise and then continue. - -We just use the up arrow until we reach the open command and issue -it again. -:: - - f = open('/home/fossee/pendulum.txt') - -Now, to read the file line-by-line, we iterate over the file -object line-by-line, using the ``for`` command. Let us iterate over -the file line-wise and print each of the lines. -:: - - for line in f: - print line - -As we already know, ``line`` is variable, sometimes called the loop -variable, and it is not a keyword. We could have used any other -variable name, but ``line`` seems meaningful enough. - -Instead of just printing the lines, let us append them to a list, -``line_list``. We first initialize an empty list, ``line_list``. -:: - - line_list = [ ] - -Let us then read the file line-by-line and then append each of the -lines, to the list. We could, as usual close the file using -``f.close`` and re-open it. But, this time, let's leave alone the -file object ``f`` and directly open the file within the for -statement. This will save us the trouble of closing the file, each -time we open it. - -:: - - for line in open('/home/fossee/pendulum.txt'): - line_list.append(line) - -Let us see what ``line_list`` contains. -:: - - line_list - -Notice that ``line_list`` is a list of the lines in the file, along -with the newline characters. If you noticed, ``pend_list`` did not -contain the newline characters, because the string ``pend`` was -split on the newline characters. - -Using some string methods, that we shall look at in the tutorial on -strings, we can strip out the newline characters from the lines. - -.. #[[Anoop: I think the code that are required to be typed can be - added to the slide.]] - -{{{ show the summary slide }}} - -That brings us to the end of this tutorial. In this tutorial we -have learnt to open and close files, read the data in the files as -a whole, using the read command or reading it line by line by -iterating over the file object. - -{{{ 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 88a01948450d -r d33698326409 getting-started-files/slides.org --- a/getting-started-files/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,73 +0,0 @@ -#+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 files -#+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 - - Opening and reading contents of a file - - Closing open files - - Reading all the contents of the file at once - - Reading files line by line -* Question 1 - Split the variable into a list, =pend_list=, of the lines in the - file. Hint, use the tab command to see what methods the string - variable has. -* Solution 1 - #+begin_src python - In []: pend_list = pend.splitlines() - - In []: pend_list - #+end_src -* Question 2 - Re-open the file =pendulum.txt= with =f= as the file object. -* Solution 2 - #+begin_src python - In []: f = open('/home/fossee/pendulum.txt') - #+end_src -* Summary - - Opening a file using =open= function - - Reading all the contents of the file at once using =read()= method - - Closing open files using the =close= method - - Reading files line by line by iterating using a =for= loop -* 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 88a01948450d -r d33698326409 getting-started-files/slides.tex --- a/getting-started-files/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,115 +0,0 @@ -% Created 2010-10-21 Thu 14:35 -\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 files} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Opening and reading contents of a file -\item Closing open files -\item Reading all the contents of the file at once -\item Reading files line by line -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Question 1} -\label{sec-2} - - Split the variable into a list, \texttt{pend\_list}, of the lines in the - file. Hint, use the tab command to see what methods the string - variable has. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 1} -\label{sec-3} - -\begin{verbatim} -In []: pend_list = pend.splitlines() - -In []: pend_list -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Question 2} -\label{sec-4} - - Re-open the file \texttt{pendulum.txt} with \texttt{f} as the file object. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 2} -\label{sec-5} - -\begin{verbatim} -In []: f = open('/home/fossee/pendulum.txt') -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-6} - -\begin{itemize} -\item Opening a file using \texttt{open} function -\item Reading all the contents of the file at once using \texttt{read()} method -\item Closing open files using the \texttt{close} method -\item Reading files line by line by iterating using a \texttt{for} loop -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-7} - - \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 88a01948450d -r d33698326409 getting-started-ipython/questions.rst --- a/getting-started-ipython/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,186 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. ``ipython`` is a programming language similar to Python. T or F? - - Answer: False - -#. Which key combination quits ``ipython``? - - a. Ctrl + C - #. Ctrl + D - #. Alt + C - #. Alt + D - - Answer: Ctrl + D - -#. Which key combination raises a ``keyboard interrupt`` - - a. Ctrl + C - #. Ctrl + D - #. Alt + C - #. Alt + D - - Answer: Ctrl + C - -#. If you have typed the following commands:: - - 1 + 2 - 3 - 5 - 1 - 6 - 5 + 5 - 3 * 2 - - What is the result of the following actions. - - * up arrow 3 times - * backspace 4 times - - Answer: 1 - -#. If you have typed the following commands:: - - 1 + 2 - 3 - 5 - 1 - 6 - 5 + 5 - 3 * 2 - - What is the result of the following actions. - - * type ``1`` - * up arrow 2 times - - Answer: 1 + 2 - -#. If you have typed the following commands:: - - 1 + 2 - 3 - 5 - 1 - 6 - 5 + 5 - 3 * 2 - - What is the result of the following actions. - - * type ``5`` - * up arrow 2 times - - Answer: 5 + 5 - -#. If you have typed the following commands:: - - 1 + 2 - 3 - 5 - 1 - 6 - 5 + 5 - 3 * 2 - - What is the result of the following actions. - - * type ``1`` - * up arrow 1 time - * left arrow 3 times - * up arrow key - - Answer: 1 - 6 - -#. If you have typed the following commands:: - - 1 + 2 - 3 - 5 - 1 - 6 - 5 + 5 - 3 * 2 - - What is the result of the following actions. - - * type ``1`` - * up arrow 1 time - * left arrow 3 times - * down arrow key - - Answer: 1 - 6 - -#. If the following are only commands available in ``ipython`` - - * zebra - * zenith - * zest - - What are the commands listed by typing ``z`` and hitting the key - - Answer: zebra, zenith, zest - -#. If the following are only commands available in ``ipython`` - - * zebra - * zenith - * zest - - ``z`` is auto-completed to ``ze`` by hitting the key after typing - ``z``. T or F? - - Answer: True - - -#. If the following are only commands available in ``ipython`` - - * zebra - * zenith - * zest - - What are the commands listed by typing ``zeb`` and hitting the key - - Answer: zebra - -#. If the following are only commands available in ``ipython`` - - * zebra - * zenith - * zest - - What are the commands listed by typing ``z`` and hitting the key - - Answer: zebra, zenith, zest - -#. Which character is used at the end of a command, in ``ipython`` to display - the documentation. - - a. _ - #. ? - #. ! - #. & - - Answer: ? - -#. What happens if the size of documentation text is more than that can be - accomodated on your screen. - - a. The whole documentation is printed and it is auto scrolled to bottom - #. Only a part of documentation is shown and the remaining can be scrolled - through using up and down arrows - #. Only a part of documentation is shown and cursor returns to ``In`` prompt - - Answer: Only a part of documentation is shown and the remaining can be - scrolled through using up and down arrows - -#. Which key is used to quit the documentation that runs several pages and - return to the ``ipython`` prompt. - - a. a - #. c - #. q - #. - - Answer: q - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) -..[[Anand: Long answer questions required]] -1. Question 1 -2. Question 2 diff -r 88a01948450d -r d33698326409 getting-started-ipython/quickref.tex --- a/getting-started-ipython/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,14 +0,0 @@ -\textbf{Getting started -- \texttt{ipython}} - -To start \lstinline|ipython| with \lstinline|pylab|:\\ -\lstinline| $ ipython -pylab| %$ - -To exit: \lstinline|^D| (Ctrl-D) - -To interrupt: \lstinline|^C| (Ctrl-C) - -Tab completes partial commands - -\texttt{?} to look up documentation. - -Arrow keys to navigate the history. diff -r 88a01948450d -r d33698326409 getting-started-ipython/script.rst --- a/getting-started-ipython/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,235 +0,0 @@ -.. Objectives -.. ---------- - -.. At the end of this tutorial, you will be able to - -.. 1. invoke the ``ipython`` interpreter. -.. #. quit the ``ipython`` interpreter. -.. #. navigate in the history of ``ipython``. -.. #. use tab-completion. -.. #. look-up documentation of functions. -.. #. interrupt incomplete or incorrect commands. - -.. Prerequisites -.. ------------- - -.. should have ``ipython`` and ``pylab`` installed. - -.. Author : Puneeth - Internal Reviewer : Anoop Jacob Thomas - Language Review : Bhanukiran - External Reviewer : - Checklist OK? : [2010-10-05] - - -Script ------- - -{{{ Show the slide containing title }}} - -Hello Friends and Welcome to the tutorial on getting started with -``ipython``. - -{{{ Show slide with outline }}} - -This tutorial will cover the basic usage of the ``ipython`` -interpreter. The following topics would be covered. - -IPython is an enhanced Python interpreter that provides features like -tabcompletion, easier access to help and lot of other functionality -which are not available in the vanilla Python interpreter. - -First let us see how to invoke the ``ipython`` interpreter. - -We type -:: - - ipython - -at the terminal prompt to invoke the ipython interpreter. - -We get a prompt with ``In [1]:`` after getting some information about -the version of Python installed and some help commands. - -If you get an error saying something like ``ipython is not -installed``, refer to the tutorial on how to install the packages -required for this course. - -Now, to quit the ipython interpreter, type Ctrl-D. You are prompted -asking if you really want to exit, type y to say yes and quit ipython. - -Start ipython again, as you did before. - -The prompt that you have says ``In [1]``. ``In`` stands for input and the -ipython interpreter is ready to accept input from you. - -Now let us see, how we can type some commands into the interpreter. - -Start with the simplest thing, addition. - -Let's type -:: - 1+2 - -at the prompt. IPython promptly gives back the output as 3. Notice -that the output is displayed with an ``Out[1]`` indication. - -.. #[[Anoop: I think we can illustrate In [] and Out[] in slides]] -.. #[[Puneeth: I think we can do that on the terminal?]] - -Let's try out few other mathematical operations. -:: - - 5 - 3 - 7 - 4 - 6 * 5 - -Now let's ``print 1+2``. Instead of typing the whole thing, we make -use of the fact that IPython remembers the history of the commands -that you have already used. We use the up arrow key to go back the -command ``1+2``. We then use the left-arrow key to navigate to the -beginning of the line and add the word ``print`` and a space. Then hit -enter and observe that the interpreter prints out the value as 3, -without the Out[] indication. - -Now, let's change the previous command ``print 1+2`` to ``print -10*2``. We use the up arrow again to navigate to the previous command -and use the left arrow key to move the cursor on to the + symbol and -then use the delete key to remove it and type 0 and * to change the -expression as required. We hit enter to see the output of -``print``. - -Now, let's say we want to use the function ``round``. We type ``ro`` -at the prompt and hit the tab key. As you can see, IPython -completes the command. This feature is called the tab-completion. - -Now, we remove all the characters and just type ``r`` and then hit -tab. IPython does not complete the command since there are many -possibilities. It just lists out all the possible completions. - -Following is an exercise that you must do. - -%%1%% Type ``ab`` and hit tab to see what happens. Next, just type -``a`` and hit tab to see what happens. - -Please, pause the video here. Do the exercise and then continue. - -``ab`` tab completes to ``abs`` and ``a`` gives us a list of all -the commands starting with a. - -Now, let's see what these functions are used for. We will use the -help features of ipython to find this out. - -.. #[[Anoop: Another slide which says about ? mark and round? etc, as - few people cannot just follow by listening (like me) :)]] - -.. #[Punch: These things are shown on the terminal. I feel we don't -.. need slide, here I guess.] - -To get the help of any function, we first type the function, ``abs`` -in our case and then add a ? at the end and hit enter. - -As the documentation says, ``abs`` accepts a number as an input and -returns it's absolute value. - -We say, -:: - - abs(-19) - - abs(19) - -We get 19, as expected, in both the cases. - -Does it work for decimals (or floats)? Let's try typing abs(-10.5) -and we do get back 10.5. - -Following is an exercise that you must do. - -%%2%% Look-up the documentation of ``round`` and see how to use it. - -Please, pause the video here. Do the exercise and then continue. - -:: - - round? - -If you notice, there are extra square brackets around the ``ndigits``. -This means that ``ndigits`` is optional and 0 is the default value. -Optional parameters are shown in square brackets anywhere in Python -documentation. - -The function ``round``, rounds a number to a given precision. - -Following are exercises that you must do. - -%%3%% Check the output of:: - - round(2.48) - round(2.48, 1) - round(2.48, 2) - - round(2.484) - round(2.484, 1) - round(2.484, 2) - -Please, pause the video here. Do the exercises and then continue. - -We get 2.0, 2.5 and 2.48, which are what we expect. - -Let's now see how to correct typing errors that we make while typing at -the terminal. As already shown, if we haven't hit the enter key -already, we could navigate using the arrow keys and make deletions -using delete or backspace key and correct the errors. - -Let's now type round(2.484 and hit enter, without closing the -parenthesis. We get a prompt with dots. This prompt is the -continuation prompt of ``ipython``. It appears, the previous line is -incomplete in some way. We now complete the command by typing, the -closing parenthesis and hitting enter. We get the expected output of -2.5. - -In other instances, if we commit a typing error with a longer and more -complex expression and end up with the continuation prompt, we can -type Ctrl-C to interrupt the command and get back the ``ipython`` input -prompt. - -Following is an exercise that you must do. - -%%4%% Try typing round(2.484, and hit enter. and then cancel the -command using Ctrl-C. Then, type the command, round(2.484, 2) and -resume the video. - -Please, pause the video here. Do the exercises and then continue. - -:: - - round(2.484 - ^C - - round(2.484, 2) - -This brings us to the end of the tutorial on getting started with -``ipython``. - -.. #[[Anoop: add slides for interrupts, navigating history, I feel - even a single point will also do]] - -.. #[Puneeth: I don't feel these things cannot be shown on a slide.] - -In this tutorial we have learnt, how to -{{{ show the outline/summary slide. }}} - - 1. invoke the ``ipython`` interpreter. - #. quit the ``ipython`` interpreter. - #. navigate in the history of ``ipython``. - #. use tab-completion. - #. look-up documentation of functions. - #. interrupt incomplete or incorrect commands. - -{{{ 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 88a01948450d -r d33698326409 getting-started-ipython/slides.org --- a/getting-started-ipython/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,99 +0,0 @@ -#+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 -- ~ipython~ -#+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 - + invoke the ~ipython~ interpreter - + quit the ~ipython~ interpreter - + navigate in the history of ~ipython~ - + use tab-completion - + look-up documentation of functions - + interrupt incomplete or incorrect commands -* Question 1 - Type =ab= and hit tab to see what happens. Next, just type =a= and - hit tab to see what happens. -* Solution 1 - =ab= tab completes to =abs= and =a= gives us a list of all the - commands starting with a. -* Question 2 - Look-up the documentation of =round= and see how to use it. -* Solution 2 - =round?= -* Question 3 - Check the output of - #+begin_src python - round(2.48) - round(2.48, 1) - round(2.48, 2) - - round(2.484) - round(2.484, 1) - round(2.484, 2) - #+end_src - Look-up the documentation of =round= and see how to use it. -* Solution 3 - We get 2.0, 2.5 and 2.48, which are what we expect. -* Question 4 - Try typing =round(2.484=, and hit enter. and then cancel the command - using Ctrl-C. Then, type the command, =round(2.484, 2)= and resume - the video. -* Solution 4 - #+begin_src python - round(2.484 - ^C - - round(2.484, 2) - #+end_src - - - -* Summary - + invoking and quitting the ~ipython~ interpreter - + navigating the history - + using tab-completion to work faster - + looking-up documentation using ~?~ - + sending keyboard interrupts using ~Ctrl-C~ - -* 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 88a01948450d -r d33698326409 getting-started-ipython/slides.tex --- a/getting-started-ipython/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,154 +0,0 @@ -% Created 2010-11-05 Fri 20:59 -\documentclass[presentation]{beamer} -\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\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}} - -\title{Getting Started -- \texttt{ipython}} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item invoke the \texttt{ipython} interpreter -\item quit the \texttt{ipython} interpreter -\item navigate in the history of \texttt{ipython} -\item use tab-completion -\item look-up documentation of functions -\item interrupt incomplete or incorrect commands -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Question 1} -\label{sec-2} - - Type \texttt{ab} and hit tab to see what happens. Next, just type \texttt{a} and - hit tab to see what happens. -\end{frame} -\begin{frame} -\frametitle{Solution 1} -\label{sec-3} - - \texttt{ab} tab completes to \texttt{abs} and \texttt{a} gives us a list of all the - commands starting with a. -\end{frame} -\begin{frame} -\frametitle{Question 2} -\label{sec-4} - - Look-up the documentation of \texttt{round} and see how to use it. -\end{frame} -\begin{frame} -\frametitle{Solution 2} -\label{sec-5} - - \texttt{round?} -\end{frame} -\begin{frame}[fragile] -\frametitle{Question 3} -\label{sec-6} - - Check the output of -\lstset{language=Python} -\begin{lstlisting} -round(2.48) -round(2.48, 1) -round(2.48, 2) - -round(2.484) -round(2.484, 1) -round(2.484, 2) -\end{lstlisting} - Look-up the documentation of \texttt{round} and see how to use it. -\end{frame} -\begin{frame} -\frametitle{Solution 3} -\label{sec-7} - - We get 2.0, 2.5 and 2.48, which are what we expect. -\end{frame} -\begin{frame} -\frametitle{Question 4} -\label{sec-8} - - Try typing \texttt{round(2.484}, and hit enter. and then cancel the command - using Ctrl-C. Then, type the command, \texttt{round(2.484, 2)} and resume - the video. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 4} -\label{sec-9} - -\lstset{language=Python} -\begin{lstlisting} -round(2.484 -^C - -round(2.484, 2) -\end{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-10} - -\begin{itemize} -\item invoking and quitting the \texttt{ipython} interpreter -\item navigating the history -\item using tab-completion to work faster -\item looking-up documentation using \texttt{?} -\item sending keyboard interrupts using \texttt{Ctrl-C} -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-11} - - \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 88a01948450d -r d33698326409 getting-started-sagenotebook/questions.rst --- a/getting-started-sagenotebook/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,28 +0,0 @@ -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 88a01948450d -r d33698326409 getting-started-sagenotebook/quickref.tex diff -r 88a01948450d -r d33698326409 getting-started-sagenotebook/script.rst --- a/getting-started-sagenotebook/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,325 +0,0 @@ -.. Objectives -.. ---------- - -.. Clearly state the objectives of the LO (along with RBT level) - -.. By the end of this tutorial, you should -- - -.. #. Know what Sage and Sage notebook are. -.. #. Be able to start a Sage shell or notebook -.. #. Be able to start using the notebook -.. #. Be able to create new worksheets -.. #. Know about the menu options available -.. #. Know about the cells in the worksheet -.. #. Be able to evaluate cells, create and delete cells, navigate them. -.. #. Be able to make annotations in the worksheet -.. #. Be able to use tab completion. -.. #. Be able to use code from other languages in the cells. - -.. Prerequisites -.. ------------- - -.. None. - -.. Author : Madhu - Internal Reviewer : Punch - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <15-11-2010, Anand, OK> [2010-10-05] - - -Script ------- - -{{{ Show the slide containing the title }}} - -Hello friends. Welcome to this spoken tutorial on Getting started with -Sage and Sage notebook. - -{{{ Show the slide containing the outline }}} - -In this tutorial, we will learn what Sage is, what is Sage notebook, -how to start and use the sage notebook. In the notebook we will be -specifically learning how to execute our code, how to write -annotations and other content, typesetting the content and how to use -the offline help available. - -{{{ Show the slide on what is Sage }}} - -To start with, What is Sage? Sage is a free, open-source mathematical -software. Sage can do a lot of math stuff for you including, but not -limited to, algebra, calculus, geometry, cryptography, graph theory -among other things. It can also be used as aid in teaching and -research in any of the areas that Sage supports. So let us start Sage -now - -{{{ Shift to terminal }}} - -We are assuming that you have Sage installed on your computer now. If -not please visit the page -http://sagemath.org/doc/tutorial/introduction.html#installation for -the tutorial on how to install Sage. - - -Let us now learn how to start Sage. On the terminal type:: - - sage - -This should start a new Sage shell with the prompt sage: which looks -like this - -{{{ Show what is displayed on the terminal }}} - -So now we can type all the commands that Sage supports here. But Sage -comes bundled with a much more elegant tool called Sage -Notebook? What is Sage Notebook? Sage Notebook provides a web based -user interface to use Sage. So once we have a Sage notebook server up -and running, all we want is a browser to access the Sage -functionality. For example there is an official instance of Sage -Notebook server running at http://sagenb.org You can visit that page, -create an account there and start using Sage! So all you need is just -a browser, a modern browser - -{{{ Intentional *cough* *cough* }}} - -#[[Bhanu: what? Are you serious?]] - -to use Sage and nothing else! The Sage notebook also provides a -convenient way of sharing and publishing our work, which is very handy -for research and teaching. - -However we can also run our own instances of Sage notebook servers on -all the computers we have a local installation of Sage. To start the -notebook server just type:: - - notebook() - -on the Sage prompt. This will start the Sage Notebook server. If we -are starting the notebook server for the first time, we are prompted -to enter the password for the admin. Type the password and make a note -of it. After this Sage automatically starts a browser page for you -with the notebook opened. - -If it doesn't automatically start a browser page check if the Notebook -server started and there were no problems. If so open your browser and -in the address bar type the URL shown in the instructions upon running -the notebook command on the sage prompt. - -{{{ The notebook() command gives an instruction telling -Open your web browser to http://localhost:8000. Point towards it }}} - -In our case it is http://localhost:{{{ Tell whatever is shown }}} - -{{{ Show the browser with Sage notebook }}} - -If you are not logged in yet, it shows the Notebook home page and -textboxes to type the username and the password. You can use the -username 'admin' and the password you gave while starting the notebook -server for the first time. There are also links to recover forgotten -password and to create new accounts. - -{{{ If you are logged in tell that you are logged in, log out and show -what is said above for the login page }}} - -Once we are logged in with the admin account we can see the notebook -admin page. A notebook can contain a collection of Sage Notebook -worksheets. Worksheet is basically a working area. This is where -we enter all the Sage commands on the notebook. - -The admin page lists all the worksheets created. On the topmost part -of this page we have the links to various pages. - -{{{ Whenever you talk on an individual link point your mouse towards -the link. For each of the link go to the page and explain as below }}} - -The home link takes us to the admin home page. The published link -takes us to the page which lists all the published worksheets. The log -link has the complete log of all the actions we did on the -notebook. We have the settings link where we can configure our notebook, -the notebook server, create and mangage accounts. We have a -link to help upon clicking opens a new window with the complete help -of Sage. The entire documentation of Sage is supplied with Sage for -offline reference and this help link is the way to get into it. Then -we can report bugs about Sage by clicking on Report a Problem link and -there is a link to sign out of the notebook. - -We can create a new worksheet by clicking New Worksheet link - -{{{ Click on the link }}} - -Sage prompts you for a name for the worksheet. Let us name the -worksheet as nbtutorial. Now we have our first worksheet which is -empty. - -A worksheet will contain a collection of cells. Every Sage command -must be entered in this cell. Cell is equivalent to the prompt on -console. When we create a new worksheet, to start with we will have -one empty cell. Let us try out some math here:: - - 2 + 2 - 57.1 ^ 100 - -The cap operator is used for exponentiation. If you observed carefully -we typed two commands but the output of only last command was -displayed. By default each cell displays the result of only the last -operation. We have to use print statement to display all the results -we want to be displayed. - -{{{ Demonstrate creating a new cell }}} - -Now to perform more operations we want more cells. So how do we create -a new cell? It is very simple. As we hover our mouse above or below -the existing cells we see a blue line, by clicking on this new line we -can create a new cell. - -We have a cell, we have typed some commands in it, but how do we -evaluate that cell? Pressing Shift along with Enter evaluates the -cell. Alternatively we can also click on the evaluate link to evaluate -the cell - -{{{ Evaluate the cell and demonstrate for both methods separately -}}}:: - - matrix([[1,2], [3,4]])^(-1) - -After we create many cells, we may want to move between the cells. To -move between the cells use Up and Down arrow keys. Also clicking on -the cell will let you edit that particular cell. - -{{{ Move between two cells created }}} - -To delete a cell, clear the contents of the cell and hit backspace - -{{{ Clear and demonstrate deleting the cell }}}:: - - Makes no sense - -If you want to add annotations in the worksheet itself on the blue -line that appears on hovering the mouse around the cell, Hold Shift -and click on the line. This creates a What You See Is What You Get -cell. - -{{{ Create a HTML editable cell }}} - -We can make our text here rich text. We can make it bold, Italics, we -can create bulleted and enumerated lists in this area:: - - This text contains both the **bold** text and also *italicised* - text. - It also contains bulleted list: - * Item 1 - * Item 2 - It also contains enumerate list: - 1. Item 1 - 2. Item 2 - -In the same cell we can display typeset math using the LaTeX like -syntax:: - - $\int_0^\infty e^{-x} \, dx$ - -We enclose the math to be typeset within $ and $ or $$ and $$ as in -LaTeX. - -We can also obtain help for a particular Sage command or function -within the worksheet itself by using a question mark following the -command:: - - sin? - -Evaluating this cell gives me the entire help for the sin function -inline on the worksheet itself. Similarly we can also look at the -source code of each command or function using double question mark:: - - matrix?? - -Sage notebook also provides the feature for autocompletion. To -autocomplete a command type first few unique characters and hit tab -key:: - - sudo - -To see all the commands starting with a specific name type those -characters and hit tab:: - - plo - -To list all the methods that are available for a certain variable or -a datatype we can use the variable name followed by the dot to access -the methods available on it and then hit tab:: - - s = 'Hello' - s.rep - -The output produced by each cell can be one of the three states. It -can be either the full output, or truncated output or hidden output. -The output area will display the error if the Sage code we wrote in -the cell did not successfully execute:: - - a, b = 10 - -{{{ Show the three states }}} - -The default output we obtained now is a truncated output. Clicking at -the left of the output area when the mouse pointer turns to hand gives -us the full output, clicking again makes the output hidden and it -cycles. - -Lastly, Sage supports a variety of languages and each cell on the -worksheet can contain code written in a specific language. It is -possible to instruct Sage to interpret the code in the language we -have written. This can be done by putting percentage sign(%) followed -by the name of the language. For example, to interpret the cell as -Python code we put:: - - %python - -as the first line in the cell. Similarly we have: %sh for shell -scripting, %fortran for Fortran, %gap for GAP and so on. Let us see -how this works. Say I have an integer. The type of the integer in -default Sage mode is -{{{ Read the output }}}:: - - a = 1 - type(a) - - Output: - -We see that Integers are Sage Integers. Now let us put %python as the -first line of the cell and execute the same code snippet:: - - %python - a = 1 - type(a) - - Output: - -Now we see that the integer is a Python integer. Why? Because now we -instructed Sage to interpret that cell as Python code. - -This brings us to the end of the tutorial on using Sage. We learnt -quite a lot about using the Notebook User Interface of Sage. We are -now confident that we can comfortably use the notebook to learn more -about Sage in the following tutorials. Let us summarize what we -learnt. In this session we learnt - - * What is Sage - * How to start Sage shell - * What is Sage notebook - * How to start the Sage notebook - * How to create accounts and start using the notebook - * How to create new worksheets - * The menus available on the notebook - * About cells in the worksheet - * Methods to evaluate the cell, create new cells, delete the cells - and navigate around the cells - * To make annotations in the worksheet - * Tab completions - * And embedding code of other scripting languages in the cells - -{{{ 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 88a01948450d -r d33698326409 getting-started-sagenotebook/slides.org --- a/getting-started-sagenotebook/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,80 +0,0 @@ -#+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 -- Sage -#+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 - - Know what Sage and Sage notebook are. - - Be able to start a Sage shell or notebook - - Be able to start using the notebook - - Be able to create new worksheets - - Know about the menu options available - - Know about the cells in the worksheet - - Be able to evaluate cells, create and delete cells, navigate them. - - Be able to make annotations in the worksheet - - Be able to use tab completion. - - Be able to use code from other languages in the cells. -* What is Sage? - - free, open-source mathematical software. - - can do a lot of math for you, including, but not limited to - + algebra - + geometry - + cryptography - + graph theory - - can be used as aid in teaching and research -* Summary - + What is Sage - + How to start Sage shell - + What is Sage notebook - + How to start the Sage notebook - + How to create accounts and start using the notebook - + How to create new worksheets - + The menus available on the notebook - + About cells in the worksheet - + Methods to evaluate the cell, create new cells, delete the cells - and navigate around the cells - + To make annotations in the worksheet - + Tab completions - + And embedding code of other scripting languages in the cells -* 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 88a01948450d -r d33698326409 getting-started-sagenotebook/slides.tex --- a/getting-started-sagenotebook/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,115 +0,0 @@ -% Created 2010-11-11 Thu 02:40 -\documentclass[presentation]{beamer} -\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\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}} - -\title{Getting started -- Sage} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Know what Sage and Sage notebook are. -\item Be able to start a Sage shell or notebook -\item Be able to start using the notebook -\item Be able to create new worksheets -\item Know about the menu options available -\item Know about the cells in the worksheet -\item Be able to evaluate cells, create and delete cells, navigate them. -\item Be able to make annotations in the worksheet -\item Be able to use tab completion. -\item Be able to use code from other languages in the cells. -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{What is Sage?} -\label{sec-2} - -\begin{itemize} -\item free, open-source mathematical software. -\item can do a lot of math for you, including, but not limited to - -\begin{itemize} -\item algebra -\item geometry -\item cryptography -\item graph theory -\end{itemize} - -\item can be used as aid in teaching and research -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-3} - -\begin{itemize} -\item What is Sage -\item How to start Sage shell -\item What is Sage notebook -\item How to start the Sage notebook -\item How to create accounts and start using the notebook -\item How to create new worksheets -\item The menus available on the notebook -\item About cells in the worksheet -\item Methods to evaluate the cell, create new cells, delete the cells - and navigate around the cells -\item To make annotations in the worksheet -\item Tab completions -\item And embedding code of other scripting languages in the cells -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-4} - - \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 88a01948450d -r d33698326409 getting-started-strings/questions.rst --- a/getting-started-strings/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,80 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. List the type of quotes that can be used to define strings. - - Answer: 'single quotes', "double quotes", - '''triple single quotes''' - """triple double quotes""" - -#. Given the strings ``s`` and ``S``, ``s='Hello World'`` and - ``S="Hello World``. s and S are different strings. True or False? - -#. What is the output of:: - - s = 'It's all here' - - Answer: ``SyntaxError`` - -#. Write code to assign s, the string ``' is called the apostrophe`` - - Answer: ``s = "`is called the apostrophe"`` - -#. Given strings s and t, ``s = "Hello"`` and ``t = "World"``. What is - the output of s + t? - - Answer: HelloWorld - -#. Given strings s and t, ``s = "Hello"`` and ``t = "World"`` and an - integer r, ``r = 2``. What is the output of s * r + s * t? - - Answer: HelloHelloWorldWorld - -#. Given strings s and t, ``s = "Hello"`` and ``t = "World"`` and an - integer r, ``r = 2``. What is the output of s * 'r' ? - - Answer: TypeError - can't multiply a sequence by non-int - -#. Given the string ``s = "Hello"``, we wish to change it to - ``hello``. what is the result of:: - - s[0] = 'h' - - Answer: TypeError - 'str' object does not support item assignment. - -#. Given the string ``s = "Hello"``, we wish to change it to - ``hello``. what is the result of:: - - s = "hello" - - Answer: s is changed to "hello" - -#. Which type of string can be written in multiple lines, with line - breaks. (Note: more than one answer may be correct.) - - #. triple double quoted strings - #. single quoted strings - #. double quoted strings - #. triple single quoted strings - - Answer: triple double quoted strings and triple single quoted strings - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Given the string s, ``s = F.R.I.E.N.D.S``, obtain the string - "FRIENDS". - - Answer:: - - s = s[0] + s[2] + s[4] + s[6] + s[8] + s[10] + s[12] - -2. Assign the string ``Today's Quote: "Don't believe in any quote, - including this."`` to the variable ``quote``. - - Answer: - quote = """Today's Quote: "Don't believe in any quote, including this.""" diff -r 88a01948450d -r d33698326409 getting-started-strings/quickref.tex --- a/getting-started-strings/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,8 +0,0 @@ -Creating a string:\\ -{\ex \lstinline| s = ``Hello World''|} -- Single quotes and triple -quotes can also be used. - -Accessing individual elements:\\ -{\ex \lstinline| s[5]|} -- Elements can be accessed with their index - -Strings are immutable. diff -r 88a01948450d -r d33698326409 getting-started-strings/script.rst --- a/getting-started-strings/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,191 +0,0 @@ -.. Objectives -.. ---------- - -.. At the end of this tutorial, you should know -- - -.. 1. How to define strings -.. #. Different ways of defining a string -.. #. How to concatenate strings -.. #. How to print a string repeatedly -.. #. Accessing individual elements of the string -.. #. Immutability of strings - -.. Prerequisites -.. ------------- - -.. 1. getting started with ipython - -.. Author : Madhu - Internal Reviewer : Punch - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <15-11-2010, Anand, OK> [2010-10-05] - -Script ------- - -{{{ Show the slide containing the title }}} - -Hello friends. Welcome to this spoken tutorial on Getting started with -strings. - -{{{ Show the slide containing the outline }}} - -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 }}} - -To begin with let us start ipython, by typing:: - - ipython - -on the terminal - -So, what are strings? In Python anything within either single quotes -or double quotes or triple single quotes or triple double quotes are -strings. - -{{{ Type in ipython the following and read them as you type }}}:: - - 'This is a string' - "This is a string too' - '''This is a string as well''' - """This is also a string""" - 'p' - "" - -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" - -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-line strings without -using any escaping. Everything within the triple quotes is a single -string no matter how many lines it extends:: - - """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.""" - -We can assign this string to any variable:: - - a = 'Hello, World!' - -Now 'a' is a string variable. String is a collection of characters. In -addition string is an immutable collection. So all the operations that -are applicable to any other immutable collection in Python works on -string as well. So we can add two strings:: - - a = 'Hello' - b = 'World' - c = a + ', ' + b + '!' - -We can add string variables as well as the strings themselves all in -the same statement. The addition operation performs the concatenation -of two strings. - -Similarly we can multiply a string with an integer:: - - a = 'Hello' - a * 5 - -gives another string in which the original string 'Hello' is repeated -5 times. - -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 and goes up to n-1 for the last character. We -can access the strings from the end using negative indices:: - - a[-1] - -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' - a[0] = 'H' - -As said earlier, strings are immutable. We cannot manipulate a -string. Although there are some methods which let us manipulate -strings, we will look at them in the advanced session on strings. In -addition to the methods that let us manipulate the strings we have -methods like split which lets us break the string on the specified -separator, the join method which lets us combine the list of strings -into a single string based on the specified separator. - -{{{ Show summary slide }}} - -This brings us to the end of another session. In this tutorial session -we learnt - - * How to define strings - * Different ways of defining a string - * String concatenation and repetition - * Accessing individual elements of the string - * Immutability of strings - -{{{ 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 88a01948450d -r d33698326409 getting-started-strings/slides.org --- a/getting-started-strings/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,80 +0,0 @@ -#+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: -#+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 strings -*** Concatenation -*** Accessing individual elements -*** Immutability of strings -* Question 1 - Obtain the string ~%% -------------------- %%~ (20 hyphens) without - typing out all the twenty hyphens. -* Solution 1 - #+begin_src python - s = "%% " + "-"*20 + " %%" - #+end_src -* Question 2 - 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 - 'W' - 'e' - IndexError - #+end_src -* Summary - 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}{} - \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 88a01948450d -r d33698326409 getting-started-strings/slides.tex --- a/getting-started-strings/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,129 +0,0 @@ -% Created 2010-11-10 Wed 10:46 -\documentclass[presentation]{beamer} -\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\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}} - -\title{} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - - - - - - - - - - - -\begin{frame} -\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{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} - - 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{Solution 2} -\label{sec-5} - -\lstset{language=Python} -\begin{lstlisting} -'W' -'e' -IndexError -\end{lstlisting} -\end{frame} -\begin{frame} -\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 - \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 88a01948450d -r d33698326409 getting-started-with-arrays/questions.rst --- a/getting-started-with-arrays/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,132 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. An array in Python is the same as a Python list - - a. True - #. False - -Answer: False - -2. ``x = array([1, 2, 3], [5, 6, 7])`` is a valid statement - - a. True - #. False - -Answer: False - -3. What will be the output of the following code, - :: - - x = array([[1, 2, 3], ['a', 2, 'c']]) - print x[0][0] + x[0][1] + x[0][2] - - a. 6 - #. 123 - #. a2c - #. Error as array takes only homogeneous elements - -Answer: 123 - -4. What will be the output of the following code, - :: - - x = [[1, 2, 3], [4.1, 4.2, 4.3], ['6','7',8]] - y = array(x) - print y[-1][-2] + y[-1][-1] + y[-2][0] + y[0][-2] - - a. 21.1 - #. 12.5 - #. 784.12 - #. Error as array takes only homogeneous elements - - .. 4.2 4.3 2 2 - -Answer: 784.12 - -5. What is the output of the following code, - :: - - x = array([[1, 2, 3], ['a', 2, 'c']]) - identity(x.shape) - - a. Will create an identity matrix of shape (2, 3). - #. ``identity()`` function takes an integer as argument and a tuple - is passed. - #. Will return, array([[1,0,1],[0,1,0]]) - #. Will return, array([[0,1,0],[0,1,0]]) - -Answer: ``identity()`` function takes an integer as argument and a - tuple is passed. - -6. ``ones_like()`` function? - - (A) Returns an array of ones with the same shape and type as a - given array. - (B) Return a new array of given shape and type, filled with ones. - - Read the statements and answer, - - a. Only statement A is correct. - #. Only statement B is correct. - #. Both statement A and B are correct. - #. Both statement A and B are incorrect. - -Answer: Only statement A is correct. - -7. ``zeros_like()`` function? - - (A) Return a new array of given shape and type, filled with zeros. - (B) Returns an array of zeros with the same shape and type as a - given array. - - - Read the statements and answer, - - a. Only statement A is correct. - #. Only statement B is correct. - #. Both statement A and B are correct. - #. Both statement A and B are incorrect. - -Answer: Only statement B is correct. - -8. What will be output of the following code snippet. - :: - - x = linspace(1,10,10).reshape(5,2) - print (x[-3]+x[-4]).sum() - - a. 10.0 - #. 18.0 - #. 14.0 - #. 16.44 - #. Error - -Answer: 18 - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Write a python script to create a 15x15 array of equally spaced 225 - elements from 1 to 1000, add 5 to each of the diagonal elements and - find the sum of all odd rows of the array. Say for example the - array, - :: - - x = array([[1, 2, 3], - [4, 5, 6], - [7, 8, 9]]) - - will give answer 40 ((1+5) + 2 + 3 + 7 + 8 + (9+5)). - -2. For any given array([a1, a2, a3, .. , an]) the Vandermonde matrix - will be [[1, a1, a1**2, .. , a1**(n-1)], [1, a2, a2**2, .. , - a2**(n-1)], .. , [1, an, an**2, .. ,an**(n-1)]]. Write a python - script to generate the Vandermonde matrix and find the determinant - of the matrix for [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20]. [Hint: to find the determinant use the - function ``det()`` from ``linalg`` module.] diff -r 88a01948450d -r d33698326409 getting-started-with-arrays/quickref.tex --- a/getting-started-with-arrays/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,14 +0,0 @@ -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 88a01948450d -r d33698326409 getting-started-with-arrays/script.rst --- a/getting-started-with-arrays/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,343 +0,0 @@ -.. Objectives -.. ---------- - -.. At the end of this tutorial, you will be able to - -.. 1. Create arrays using data -.. #. Create arrays from lists -.. #. Basic array operations -.. #. Creating identity matrix using ``identity()`` function. -.. #. Learn about ``zeros()``, ``zeros_like()``, ``ones()``, - ``ones_like()`` functions. - -.. Prerequisites -.. ------------- - -.. 1. should have ``ipython`` and ``pylab`` installed. -.. #. getting started with ``ipython``. -.. #. getting started with lists. - -.. Author: Anoop Jacob Thomas - Internal Reviewer : Puneeth - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <11-11-2010,Anand, OK > [2010-10-05] - -=========================== -Getting started with Arrays -=========================== - -.. #[Puneeth: Prerequisites and Objectives are missing. Fill them in] - -{{{ show the welcome slide }}} - -Welcome to the spoken tutorial on getting started with arrays. - -{{{ switch to next slide, outline slide }}} - -In this tutorial, we will learn about the data structure called an array, how to convert -a list into an array, operations on arrays and also why an array is preferred -to lists. - -.. #[Puneeth: Fix the grammar above.] - -{{{ switch to next slide on overview of array }}} - -Arrays are homogeneous data structures. Unlike lists, arrays cannot have -heterogeneous data elements, that is, they can have only one type of data -as their entries, be them all integers, strings, or maybe floats, but not a mix. - -.. #[Puneeth: Use multiple short sentences, rather than one long sentence - I would've written something like this. - - Unlike lists, arrays are homogeneous data structures. They can have only - type of data, ....] - -Arrays of a given length are comparatively much faster in mathematical -operations than lists of the same length, because of the fact that they are -homogeneous data structures. - -.. #[Puneeth: For what size of an array is that the comparison? - -{{{ switch to the next slide, creating arrays }}} - -Now let us see how to create arrays. - -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?] - -To create an array we will use the function ``array()`` as, - -:: - - a1 = array([1,2,3,4]) - -Notice that we created a one dimensional array here. Also notice the object -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 -.. concepts learnt? ] - -.. #[Puneeth: Also, you didn't even point out that we are converting a -.. list, using the ``array`` function. Bring the later section about -.. converting a list, here. A separate section is not necessary, IMHO.] - -We create two dimensional array by converting a list of lists to an array -as, - -:: - - a2 = array([[1,2,3,4],[5,6,7,8]]) - -.. #[Puneeth: Again, you could explain a bit about the fact that we are -.. converting a list of lists.] - -Now let us use ``arange()`` function to create the same array as before. - -:: - - ar = arange(1,9) - -.. #[Puneeth: say, creating the same array as before. for some time I got -.. confused .] - -And we obtained a one dimensional array with elements from 1 to 8. - -:: - - print ar - -.. #[Puneeth: be consistent with voice. say, we obtained... or something.] - -And how can we make it a two dimensional array of order 2 by 4? Pause here -and try to do it yourself, try ``ar.tab`` and find a suitable method for -that. - -{{{ switch to next slide, reshape() method }}} - -We can use the function ``reshape()`` for that purpose and it can be done -as, - -:: - - ar.reshape(2,4) - ar.reshape(4,2) - ar = ar.reshape(2,4) - -{{{ switch to next slide, creating array from list}}} - -Now, let us see how to convert a list object to an array. As you have -already seen, in both of the previous statements we have passed a list, so -creating an array can be done so, first let us create a list ``l1`` - -:: - - l1 = [1,2,3,4] - -Now we can convert the list to an array as, - -:: - - a3 = array(l1) - - -{{{ switch to the next slide, problem statement of unsolved exercise 1 }}} - -Create a three dimensional array of the shape (2,2,4). - -.. #[Puneeth: s/order/shape or size ?] - -{{{ switch to the next slide, shape of an array }}} - -To find the shape of an array we can use the method ``.shape``, let us -check the shape of the arrays we have created so far, - -.. #[Puneeth: s/object/method ?] - -:: - - a2.shape - -``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. ] - -{{{ switch to the next slide, unsolved exercise 2 }}} - -Find out the shape of the other arrays that we have created. - -.. #[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 -.. keep this, just briefly mention that arrays are homogeneous in the -.. intro, don't explain it there.] - -Now let us try to create a new array with a mix of elements and see what -will happen, - -:: - - a4 = array([1,2,3,'a string']) - -Well, we would expect an error as it has been previously mentioned that arrays handle -elements with the same datatype, but it didn't raise an error. Let us check the values -in the new array created. In your IPython terminal type, -:: - - a4 - -Did you notice it, - -{{{ switch to next slide, implicit type casting }}} - -.. #[Puneeth: typecasting may be unnecessary. (Also too advanced?) an -.. average guy wouldn't use arrays with strings.] - -.. #[Puneeth: You may want to mention that float is the default dtype.] - -{{{ highlight all the array elements one by one using mouse movements }}} - -all the elements have been implicitly type casted as strings, though our -first three elements were meant to be integers. - -.. #[Puneeth: when I type a4 it says some ``dtype`` etc. I don't understand -.. what it is, can you explain? ;)] - -{{{ switch to the next slide, identity & zeros methods }}} - -.. #[Puneeth: something needs to motivate this. why are we suddenly talking -.. of an identity matrix?] - -Now let us see how to create an identity matrix of a given size, that is a -two-dimensional array in which all the diagonal elements are ones and rest of the -elements are zeros. We can create an identity matrix using the function -``identity()``. - -The function ``identity()`` takes an integer argument which specifies the -size of the desired matrix, - -:: - - identity(3) - -As you can see the identity function returned a three by three square matrix -with all the diagonal elements as ones and the rest of the elements as zeros. - -.. #[Puneeth: You say array here, matrix there -- it's a bit messed up. -.. Clarify, explicitly.] - -``zeros()`` function accepts a tuple, which is the order of the array that we -want to create, and it generates an array with all elements as zeros. - -{{{ switch to the next slide, problem statement of solved exercise 1 }}} - -Let us creates an array of the order four by five with all the elements -zero. We can do it using the method zeros, :: - - zeros((4,5)) - -Notice that we passed a tuple to the function zeros. - -{{{ switch to next slide, learning exercise }}} - -We learned two functions ``identity()`` and ``zeros()``, find out more -about the functions ``zeros_like()``, ``ones()``, ``ones_like()``. - -{{{ switch to next slide, array operations }}} - -Try the following, first check the value of a1, -:: - - a1 - -``a1`` is a single dimensional array, and now try, -:: - - a1 * 2 - -It returned a new array with all the elements multiplied by 2. -:: - - a1 - -note that the value of a1 still remains the same. - -Similarly with addition, -:: - - a1 + 2 - -it returns a new array, with all the elements summed with two. But -again notice that the value of a1 has not been changed. -:: - - a1 - -You may change the value of a1 by simply assigning the newly returned -array as, -:: - - a1 += 2 - -Notice the change in elements of a, -:: - - a - -We can use all the mathematical operations with arrays, Now let us try this -:: - - a1 = array([1,2,3,4]) - a2 = array([1,2,3,4]) - a1 + a2 - -Returns an array with element by element addition, -:: - - a1 * a2 - -Returns an array with element by element multiplication, notice that it -does not perform matrix multiplication. - -{{{ switch to next slide, summary slide }}} - -So this brings us to the end of this tutorial, in this tutorial we covered -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] - -{{{ switch to next slide, thank you }}} - -Thank you! - -.. - Local Variables: - mode: rst - indent-tabs-mode: nil - sentence-end-double-space: nil - fill-column: 75 - End: diff -r 88a01948450d -r d33698326409 getting-started-with-arrays/slides.org --- a/getting-started-with-arrays/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,135 +0,0 @@ -#+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 arrays -#+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 - - Arrays - - why arrays over lists - - Creating arrays - - Array operations - -* Overview of Arrays - - Arrays are homogeneous data structures. - - elements have to the same data type - - Arrays are faster compared to lists - - at least /80-100 times/ faster than lists - -* 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]]) - 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 - : In []: ar.reshape(2, 4) - : In []: ar.reshape(4, 2) - : In []: ar = ar.reshape(2, 4) - -* Creating ~array~ from ~list~. - - ~array()~ method accepts list as argument - - Creating a list - : In []: l1 = [1, 2, 3, 4] - - Creating an array - : In []: a3 = array(l1) - -* Exercise 1 - Create a 3-dimensional array of the order (2, 2, 4). - -* ~.shape~ of array - - ~.shape~ - To find the shape of the array - : In []: a2.shape - - ~.shape~ - returns a tuple of shape -* Exercise 2 - 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']) -* Implicit type casting - : In []: a4 - All elements are type casted to string type -* ~identity()~, ~zeros()~ methods - - ~identity(n)~ - Creates an identity matrix, a square matrix of order (n, n) with diagonal elements 1 and others 0. - - ~zeros((m, n))~ - Creates an ~m X n~ matrix with all elements 0. - -* Learning exercise - - Find out about - - ~zeros_like()~ - - ~ones()~ - - ~ones_like()~ - -* Array operations - - ~a1 * 2~ - returns a new array with all elements of ~a1~ multiplied by ~2~. - - Similarly ~+~, ~-~ \& ~/~. - - ~a1 + 2~ - returns a new array with all elements of ~a1~ summed with ~2~. - - ~a1 += 2~ - adds ~2~ to all elements of array ~a1~. - - Similarly ~-=~, ~*=~ \& ~/=~. - - ~a1 + a2~ - does elements-wise addition. - - Similarly ~-~, ~*~ \& ~/~. - - ~a1 * a2~ - does element-wise multiplication - - *Note* - array(A) * array(B) does element wise multiplication and not matrix multiplication - -* Summary - In this tutorial we covered, - - Basics of arrays - - Creating arrays - - Arrays from lists - - Basic array operations - -* 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 88a01948450d -r d33698326409 getting-started-with-arrays/slides.tex --- a/getting-started-with-arrays/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,284 +0,0 @@ -% Created 2010-11-07 Sun 15:18 -\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 arrays} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Arrays - -\begin{itemize} -\item why arrays over lists -\end{itemize} - -\item Creating arrays -\item Array operations -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Overview of Arrays} -\label{sec-2} - -\begin{itemize} -\item Arrays are homogeneous data structures. - -\begin{itemize} -\item elements have to the same data type -\end{itemize} - -\item Arrays are faster compared to lists - -\begin{itemize} -\item at least \emph{80-100 times} faster than lists -\end{itemize} - -\end{itemize} -\end{frame} -\begin{frame}[fragile] -\frametitle{Creating Arrays} -\label{sec-3} - -\begin{itemize} -\item Creating a 1-dimensional array -\end{itemize} - -\begin{verbatim} - 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} - -\begin{verbatim} - 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} - -\begin{verbatim} - In []: ar = arange(1,9) -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{\texttt{reshape()} method} -\label{sec-5} - -\begin{itemize} -\item To reshape an array -\end{itemize} - -\begin{verbatim} - In []: ar.reshape(2, 4) - In []: ar.reshape(4, 2) - In []: ar = ar.reshape(2, 4) -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Creating \texttt{array} from \texttt{list}.} -\label{sec-6} - -\begin{itemize} -\item \texttt{array()} method accepts list as argument -\item Creating a list -\begin{verbatim} - In []: l1 = [1, 2, 3, 4] -\end{verbatim} - -\item Creating an array -\begin{verbatim} - In []: a3 = array(l1) -\end{verbatim} - -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Exercise 1} -\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-8} - -\begin{itemize} -\item \texttt{.shape} - To find the shape of the array -\begin{verbatim} - In []: a1.shape -\end{verbatim} - -\item \texttt{.shape} - returns a tuple of shape -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Exercise 2} -\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-10} - -\begin{itemize} -\item All elements in array should be of same type -\begin{verbatim} - In []: a4 = array([1,2,3,'a string']) -\end{verbatim} - -\end{itemize} -\end{frame} -\begin{frame}[fragile] -\frametitle{Implicit type casting} -\label{sec-11} - -\begin{verbatim} - In []: a4 -\end{verbatim} - - All elements are type casted to string type -\end{frame} -\begin{frame} -\frametitle{\texttt{identity()}, \texttt{zeros()} methods} -\label{sec-12} - -\begin{itemize} -\item \texttt{identity(n)} - Creates an identity matrix, a square matrix of order (n, n) with diagonal elements 1 and others 0. -\item \texttt{zeros((m, n))} - Creates an \texttt{m X n} matrix with all elements 0. -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Learning exercise} -\label{sec-13} - -\begin{itemize} -\item Find out about - -\begin{itemize} -\item \texttt{zeros\_like()} -\item \texttt{ones()} -\item \texttt{ones\_like()} -\end{itemize} - -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Array operations} -\label{sec-14} - -\begin{itemize} -\item \texttt{a1 * 2} - returns a new array with all elements of \texttt{a1} multiplied by \texttt{2}. - -\begin{itemize} -\item Similarly \texttt{+}, \texttt{-} \& \texttt{/}. -\end{itemize} - -\item \texttt{a1 + 2} - returns a new array with all elements of \texttt{a1} summed with \texttt{2}. -\item \texttt{a1 += 2} - adds \texttt{2} to all elements of array \texttt{a1}. - -\begin{itemize} -\item Similarly \texttt{-=}, \texttt{*=} \& \texttt{/=}. -\end{itemize} - -\item \texttt{a1 + a2} - does elements-wise addition. - -\begin{itemize} -\item Similarly \texttt{-}, \texttt{*} \& \texttt{/}. -\end{itemize} - -\item \texttt{a1 * a2} - does element-wise multiplication -\end{itemize} - - - \textbf{Note} - array(A) * array(B) does element wise multiplication and not matrix multiplication -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-15} - - In this tutorial we covered, -\begin{itemize} -\item Basics of arrays -\item Creating arrays -\item Arrays from lists -\item Basic array operations -\end{itemize} -\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 88a01948450d -r d33698326409 getting-started-with-for/questions.rst --- a/getting-started-with-for/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,115 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. In Python a block is represented by - - a. Curly braces - #. Begin and End keywords - #. Indentation - #. Curly braces + Indentation - #. All of the above - -Answer: Indentation - -2. Indentation is not mandatory in Python - - a. True - #. False - -Answer: False - -3. A ``for`` loop in Python, - - a. is a simple iterator - #. is a condition based loop - #. can iterate only over integer list of elements - #. All of the above - -Answer: is a simple iterator - -4. ``range()`` function can generate negative numbers - - a. True - #. False - -Answer: True - -5. ``range(a,b)`` function returns, - - a. A tuple of elements from a to b including a and b - #. A tuple of elements from a to b excluding b - #. A list of elements from a to b including a and b - #. A list of elements from a to b excluding b - -Answer: A list of elements from a to b excluding b - -6. ``linspace(1,100,2)`` and ``range(1,100,2)`` produces the same output, - - a. True - #. False - -Answer: False - -7. What is the output of the below code snippet? - :: - - y = 1 - for x in range(21): - y*=x - print y - - a. Product of natural numbers up to 20(including) - #. Product of natural numbers up to 21(including) - #. Zero - #. Error - -Answer: Zero - -8. What is the output of the below code snippet? - :: - - y = 1 - for x in range(1,21): - y*=x - print y - - a. Product of natural numbers up to 20(including) - #. Product of natural numbers up to 21(including) - #. Zero - #. Error - -Answer: Product of natural numbers up to 20(including) - -9. What is the output of the below code snippet? - :: - - y = 1 - for x in range(1,21) - y*=x - print y - - a. Product of natural numbers up to 20(including) - #. Product of natural numbers up to 21(including) - #. Zero - #. Error - -Answer: Error - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Write a python script to calculate the sum of the first 1000 - natural numbers? - -2. Write a python script to find out prime numbers up to 500. - [`hint`: a number ``A`` which is divisible by only ``1`` and ``A`` - is a prime number.] - -3. Write a python script to find out the difference between the - square of sum of first 100 natural numbers and sum of squares of - first 100 natural numbers. - diff -r 88a01948450d -r d33698326409 getting-started-with-for/quickref.tex --- a/getting-started-with-for/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,6 +0,0 @@ -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 88a01948450d -r d33698326409 getting-started-with-for/script.rst --- a/getting-started-with-for/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,308 +0,0 @@ -.. Objectives -.. ---------- - -.. At the end of this tutorial, you will be able to - -.. 1. Write blocks of code in python. -.. #. Use for loop. -.. #. Use ``range()`` function. -.. #. Write blocks in python interpreter -.. #. Write blocks in ipython interpreter. - - -.. Prerequisites -.. ------------- - -.. 1. should have ``ipython`` and ``pylab`` installed. -.. #. getting started with ``ipython``. -.. #. getting started with lists. - - -.. Author : Anoop Jacob Thomas - Internal Reviewer : Nishanth - Internal Reviewer(2): Amit - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <10-11-2010, Anand, OK> [2010-10-05] - - -============================= -Getting started with for loop -============================= - -{{{ show welcome slide }}} - -Hello and welcome to the tutorial `Getting started with ``for`` loop`. - -{{{ switch to next slide, outline slide }}} - -In this tutorial we will learn about ``for`` loops in python, and also -learn how to write blocks of code in Python. - -.. #[Nishanth]: Instead of saying basics of indenting code, - say How to define code blocks in Python - -{{{ switch to next slide, about whitespaces }}} - -In Python whitespace is significant, and the blocks are visually -separated. - -.. #[nishanth]: Simply tell how blocks are defined in python. - The details like braces are not used and its - advantages like neat code can be told after completely - explaining the indentation - -.. #[Amit]: Do you want to do that here. May be its better to talk about - this after some initiation into the idea of blocks. - -The best practice is to indent the code using four spaces. - -.. #[Nishanth]: Even this detail may be skipped. Simply say use 4 spaces - for indentation. Do that while typing so that they can - actually see what is being typed. - -As you can see in the slide, ``Block B`` is an inner block and it is -indented using 4 spaces, and after ``Block B`` the next statement in -``Block A`` starts from the same indentation level of other ``Block -A`` statements. - -Now let us move straight into ``for`` loop. - -{{{ switch to next slide, problem statement of exercise 1 }}} - - -Write a for loop which iterates through a list of numbers and find the -square root of each number. -:: - - numbers are 1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916 - -.. #[nishanth]: making new list with square roots induces extra complication - like appending which has no use case here - -.. #[Nishanth]: The problem focuses more on square root and creation - of list. The problem must be simple and focusing on - nothing more but the indentation and for loop. - May be change the problem to print squares than to - print square roots. - -For the problem, first we need to create a ``list`` of numbers and -then iterate over the list and find the square root of each element in -it. And let us create a script, rather than typing it out in the -interpreter itself. Create a script called list_roots.py and type the -following. - -{{{ open the text editor and paste the following code there }}} -:: - - numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] - for each in numbers: - print "Square root of", each, "is", sqrt(each) - print "This is not in for loop!" - -.. numbers = [1, 12, 3, 4, 21, 17] - for each in numbers: - print each, each * each - -.. #[nishanth]: I don't see a use case to append the sq_root to - square_roots. It is only complicating stuff. - Simply iterate and print. - -{{{ switch to next slide, save and run script }}} - -{{{ save the script }}} - -Now save the script, and run it from your IPython interpreter. I -assume that you have started your IPython interpreter using ``-pylab`` -option. - -Run the script as, -:: - - %run -i list_roots.py - -.. #[Nishanth]: you don't have to use the -i option here - -{{{ run the script }}} - -So that was easy! All what we did was iterate over the list element by -element and then use the element for calculation. Note that here we -used two variables. One the variable ``numbers``, which is a list, -another one ``each``, which is the element of list under consideration -in each cycle of the ``for`` loop. The variable names can be chosen by -you. - -.. #[Nishanth]: The details like we didn't have to find the length - are relevant for people who have programmed in C or - other languages earlier. But for a newbie it is more - of confusing extra info. That part may be skipped. - Simply go ahead and focus on the syntax of for loop. - And how the variable name is used inside the for loop. - If you modify the question to only print, the extra - variable sq_root can also be avoided. let it be more - about "each", "numbers" and "for". no other new names. - -{{{ show the script which was created }}} - -Note that the lines after ``for`` statement, is indented using four -spaces. - -{{{ highlight the line after for statement }}} - -It means that line is part of the for loop. And it is a block of code, -although it is only a single statement in the block. And the fourth -line or the immediate line after the ``for`` block is not indented, - -{{{ highlight the fourth line - the line just after for loop }}} - -it means that it is not part of the ``for`` loop and the lines after -that doesn't fall in the scope of the ``for`` loop. Thus each block is -separated by the indentation level and that marks the importance of -white-spaces in Python. - -{{{ switch to the slide which shows the problem statement of the first -problem to be tried out }}} - -Now a question for you to try, from the given numbers make a list of -perfect squares and a list of those which are not. The numbers are, -:: - - 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}}} - -Now let us try a simple one, to print the square root of numbers in -the list. And this time let us do it right in the IPython -interpreter. - -{{{ switch to next slide, Indentation in ``ipython`` }}} - -{{{ switch focus to the IPython interpreter }}} - -So let us start with making a list. Type the following -:: - - numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] - for each in numbers: - -and now you will notice that, as soon as you press the return key -after for statement, the prompt changes to four dots and the cursor is -not right after the four dots but there are four spaces from the -dots. Please note that IPython automatically indents the block. The -four dots tell you that you are inside a block. Now type the rest of -the ``for`` loop, - -{{{ switch to next slide, Indentation in ``ipython`` (cont'd) }}} - -.. #[Nishanth]: Tell that IPython does auto indentation. - -:: - - print "Square root of", each, - print "is", sqrt(each) - -Now we have finished the statements in the block, and still the -interpreter is showing four dots, this means that you are still inside the -block. To exit from the block press the return key or the enter key twice -without entering anything else. It printed the square root of each -number in the list, and that is executed in a ``for`` loop. - -{{{ switch to next slide, Indentation in ``python`` interpreter }}} - -Now, let us find the cube of all the numbers from one to ten. But this -time let us try it in the vanilla version of Python interpreter. - -Start the vanilla version of Python interpreter by issuing the command -``python`` in your terminal. - -{{{ open the python interpreter in the terminal using the command -python to start the vanilla Python interpreter }}} - -{{{ switch to next slide, Indentation in ``python`` interpreter -(cont'd) }}} - -Start with, -:: - - for i in range(1,11): - -and press enter once, and we will see that this time it shows four -dots, but the cursor is close to the dots, so we have to indent the -block. The vanilla version of Python interpreter does not indent the -code automatically. So enter four spaces there and then type the -following -:: - - print i, "cube is", i**3 - -Now when we hit enter, we still see the four dots, to get out of the -block, hit enter once again - -.. #[Nishanth]: Here also the overhead on print can be reduced. - Think of a simple print statement. This statement - will be confusing for a newbie. - We can focus more on indentation in python. - -.. #[nishanth]: Not sure if you must use range here. You can - define a list of numbers and iterate on it. - Then say this list can also be generated using - the range function and hence introduce range. - -{{{ switch to the next slide, ``range()`` function }}} - -Okay! so the main thing that we learned here is how to use Python -interpreter and IPython interpreter to specify blocks. But while we -were generating the multiplication table we used something new, -``range()`` function. ``range()`` is an inbuilt function in Python -which can be used to generate a ``list`` of integers from a starting -number to an ending number. Note that the ending number that you -specify will not be included in the ``list``. - -.. #[Nishanth]: Show some examples of range without the step argument - May be give an exercise with negative numbers as arguments - -{{{ switch to next slide, problem statement of the next problem in -solved exercises }}} - -Now, let us print all the odd numbers from 1 to 50. Pause here and try -to solve the problem yourself. - -Let us do it in our IPython interpreter for ease of use. - -{{{ switch focus to ipython interpreter }}} - -The problem can be solved by just using the ``range()`` function. - -It can be solved as, -:: - - print range(1,51,2) - -This time we passed three parameters to ``range()`` function unlike -the previous case where we passed only two parameters. The first two -parameters are the same in both the cases. The first parameter is the -starting number of the sequence and the second parameter is the end of -the range. Note that the sequence doesn't include the ending -number. The third parameter is for stepping through the sequence. Here -we gave two which means we are skipping every alternate element. - -{{{ switch to next slide, summary slide }}} - -Thus we come to the end of this tutorial. We learned about blocks in -Python, indentation, blocks in IPython, for loop, iterating over a -list and then the ``range()`` function. - -.. #[Amit]: There does seem to too much overhead of details. Should - the first example be done using script is it necessary. - Do add some things in evolutionary manner. Like introducing - range as a list and doing a very very simple for loop.Like - iterating over [1,2,3] .Before getting into a problem. - And club details about problem in one paragraph and syntactic details - in other. - -{{{ switch to next slide, thank you slide }}} - -Thank you! diff -r 88a01948450d -r d33698326409 getting-started-with-for/slides.org --- a/getting-started-with-for/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,146 +0,0 @@ -#+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 for -#+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 - - ~for~ loop in Python. - - Blocks of code in Python. - - Indentation -* Whitespace in Python - - Whitespace is significant - - blocks are visually separated - - Blocks are indented using 4 spaces - : Block A - : Block A - : Block B - : Block B - : Block A - ~Block B~ is an inner block and is indented using 4 spaces -* Exercise 1 - Write a ~for~ loop which iterates through a list of numbers and find - the square root of each number. - : - The numbers are, - : 1369, 7225, 3364, 7056, 5625, 729, 7056, - : 576, 2916 -* Solution 1 - - Open text editor and type the following code - #+begin_src python - numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, - 576, 2916] - - for each in numbers: - print "Square root of", each, "is", sqrt(each) - - print "This is not in for loop!" - #+end_src -* Save \& run script - - Save the script as ~list_roots.py~ - - Run in ~ipython~ interpreter as, - : In []: %run -i list_roots.py -* Exercise 2 - From the given numbers make a list of perfect squares and a list of those which are not. - : - The numbers are, - : 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, - : 7056, 576, 2916 -* Exercise 3 (indentation in ~ipython~) - Print the square root of numbers in the list. - : - Numbers are, - : 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, - : 7056, 576, 2916 -* Indentation in ~ipython~ - : In []: numbers = [1369, 7225, 3364, 7056, 5625, - : ...: 729, 7056, 576, 2916] - - : In []: for each in numbers: - : ...: - Note the four spaces here - : - : - : - : - : - : -* Indentation in ~ipython~ (cont'd) - : In []: numbers = [1369, 7225, 3364, 7056, 5625, - : ...: 729, 7056, 576, 2916] - : In []: for each in numbers: - : ...: - Note the four spaces here - : - Now type the rest of the code - : ...: print "Square root of", each, - : ...: print "is", sqrt(each) - : ...: - : ...: -* Indentation in ~python~ interpreter - Find out the cube of all the numbers from 1 to 10. - : - /do it in the python interpreter/ -* Indentation in ~python~ interpreter (cont'd) - #+begin_src python - >>> for i in range(1, 11): - ... print i, "cube is", i**3 - ... - #+end_src -* ~range()~ function - - in built function in Python - - generates a list of integers - - /syntax:/ range([start,] stop[, step]) - - /example:/ - - range(1, 20) - /generates integers from 1 to 20/ - - range(20) - /generates integers from 0 to 20/ -* Exercise 4 - Print all the odd numbers from 1 to 50. -* Summary - - blocks in ~python~ - - indentation - - blocks in ~ipython~ interpreter - - ~for~ loop - - iterating over list using ~for~ loop - - ~range()~ function -* 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 88a01948450d -r d33698326409 getting-started-with-for/slides.tex --- a/getting-started-with-for/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,285 +0,0 @@ -% Created 2010-10-12 Tue 12:55 -\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 for} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item \texttt{for} loop in Python. -\item Blocks of code in Python. - -\begin{itemize} -\item Indentation -\end{itemize} - -\end{itemize} -\end{frame} -\begin{frame}[fragile] -\frametitle{Whitespace in Python} -\label{sec-2} - -\begin{itemize} -\item Whitespace is significant - -\begin{itemize} -\item blocks are visually separated -\end{itemize} - -\item Blocks are indented using 4 spaces -\begin{verbatim} - Block A - Block A - Block B - Block B - Block A -\end{verbatim} - - \texttt{Block B} is an inner block and is indented using 4 spaces -\end{itemize} -\end{frame} -\begin{frame}[fragile] -\frametitle{Exercise 1} -\label{sec-3} - - Write a \texttt{for} loop which iterates through a list of numbers and find - the square root of each number. -\begin{verbatim} - -\end{verbatim} - - The numbers are, -\begin{verbatim} - 1369, 7225, 3364, 7056, 5625, 729, 7056, - 576, 2916 -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 1} -\label{sec-4} - -\begin{itemize} -\item Open text editor and type the following code -\end{itemize} - -\begin{verbatim} -numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, - 576, 2916] - -for each in numbers: - print "Square root of", each, "is", sqrt(each) - -print "This is not in for loop!" -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Save \& run script} -\label{sec-5} - -\begin{itemize} -\item Save the script as \texttt{list\_roots.py} -\item Run in \texttt{ipython} interpreter as, -\begin{verbatim} - In []: %run -i list_roots.py -\end{verbatim} - -\end{itemize} -\end{frame} -\begin{frame}[fragile] -\frametitle{Exercise 2} -\label{sec-6} - - From the given numbers make a list of perfect squares and a list of those which are not. -\begin{verbatim} - -\end{verbatim} - - The numbers are, -\begin{verbatim} - 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, - 7056, 576, 2916 -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Exercise 3 (indentation in \texttt{ipython})} -\label{sec-7} - - Print the square root of numbers in the list. -\begin{verbatim} - -\end{verbatim} - - Numbers are, -\begin{verbatim} - 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, - 7056, 576, 2916 -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Indentation in \texttt{ipython}} -\label{sec-8} - -\begin{verbatim} - In []: numbers = [1369, 7225, 3364, 7056, 5625, - ...: 729, 7056, 576, 2916] -\end{verbatim} - - -\begin{verbatim} - In []: for each in numbers: - ...: -\end{verbatim} - - Note the four spaces here -\begin{verbatim} - - - - - - -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Indentation in \texttt{ipython} (cont'd)} -\label{sec-9} - -\begin{verbatim} - In []: numbers = [1369, 7225, 3364, 7056, 5625, - ...: 729, 7056, 576, 2916] - In []: for each in numbers: - ...: -\end{verbatim} - - Note the four spaces here -\begin{verbatim} - -\end{verbatim} - - Now type the rest of the code -\begin{verbatim} - ...: print "Square root of", each, - ...: print "is", sqrt(each) - ...: - ...: -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Indentation in \texttt{python} interpreter} -\label{sec-10} - - Find out the cube of all the numbers from 1 to 10. -\begin{verbatim} - -\end{verbatim} - - \emph{do it in the python interpreter} -\end{frame} -\begin{frame}[fragile] -\frametitle{Indentation in \texttt{python} interpreter (cont'd)} -\label{sec-11} - -\begin{verbatim} ->>> for i in range(1, 11): -... print i, "cube is", i**3 -... -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{\texttt{range()} function} -\label{sec-12} - -\begin{itemize} -\item in built function in Python -\item generates a list of integers - -\begin{itemize} -\item \emph{syntax:} range([start,] stop[, step]) -\item \emph{example:} - -\begin{itemize} -\item range(1, 20) - \emph{generates integers from 1 to 20} -\item range(20) - \emph{generates integers from 0 to 20} -\end{itemize} - -\end{itemize} - -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Exercise 4} -\label{sec-13} - - Print all the odd numbers from 1 to 50. -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-14} - -\begin{itemize} -\item blocks in \texttt{python} -\item indentation -\item blocks in \texttt{ipython} interpreter -\item \texttt{for} loop -\item iterating over list using \texttt{for} loop -\item \texttt{range()} function -\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 88a01948450d -r d33698326409 getting-started-with-functions/questions.rst --- a/getting-started-with-functions/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,112 +0,0 @@ -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 88a01948450d -r d33698326409 getting-started-with-functions/quickref.tex --- a/getting-started-with-functions/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,4 +0,0 @@ -Defining a function:\\ -{\ex \lstinline| def name([arguments]):|} -{\ex \lstinline| code|} -{\ex \lstinline| [return values]|} diff -r 88a01948450d -r d33698326409 getting-started-with-functions/script.rst --- a/getting-started-with-functions/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,293 +0,0 @@ -.. 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 : - Language Reviewer : Bhanukiran - 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 as many times as needed. 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 4 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 and the second line is used to -fix what the function is supposed to return. ``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's 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 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 in the number n are even, -.. returns False if all the digits in the number n are 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 88a01948450d -r d33698326409 getting-started-with-functions/slides.org --- a/getting-started-with-functions/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,211 +0,0 @@ -#+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 88a01948450d -r d33698326409 getting-started-with-functions/slides.tex --- a/getting-started-with-functions/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,318 +0,0 @@ -% 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 88a01948450d -r d33698326409 getting-started-with-lists/questions.rst --- a/getting-started-with-lists/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,56 +0,0 @@ -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 88a01948450d -r d33698326409 getting-started-with-lists/questions.rst.orig --- a/getting-started-with-lists/questions.rst.orig Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,56 +0,0 @@ -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 88a01948450d -r d33698326409 getting-started-with-lists/quickref.tex --- a/getting-started-with-lists/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,19 +0,0 @@ -Creating an list\\ -{\ex \lstinline| empty=[]|} - -Create a filled list\\ -{\ex \lstinline| nonempty = ['spam', 'eggs', 100, 1.234] |} - -Accessing a list\\ -{\ex \lstinline| nonempty[0] |} -{\ex \lstinline| nonempty[-1] |} - -Length of a list\\ -{\ex \lstinline| len(nonempty) |} - -Append an element to a list\\ -{\ex \lstinline| nonempty.append('python') |} - -Remove elements of a list\\ -{\ex \lstinline| del(nonempty[1] |} -{\ex \lstinline| nonempty.remove(100) |} diff -r 88a01948450d -r d33698326409 getting-started-with-lists/script.rst --- a/getting-started-with-lists/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,242 +0,0 @@ -.. 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 : - Language Reviewer : Bhanukiran - Checklist OK? : <12-11-2010, Anand, 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 mutually -different datatypes. List is also a sequence data type, all the -elements are arranged in a given order. - -.. #[[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 (or items) between two square brackets. - -As we can see lists can contain different kinds of data. In the -previous example 'spam' and 'eggs' are strings whereas 100 and 1.234 are -integer and float respectively. Thus we can put elements of different types in -lists including lists itself. This property makes lists heterogeneous -data structures. - -.. #[[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 an element of a list using its corresponding index. Index of -the first element of a list is 0. So for the 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 the last which, in this case, is the first element. - -We can append elements to the end of a list using the method append. :: - - 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 nonempty is appended with 'onemore' and 6 at the end. - -Using len function we can check the number of elements in the list -nonempty. In this case it is 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, 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 -would 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 -and therefore `remove` removes the first occurence of the element in the sequence -and leaves others untouched. - -One should remember this that while del removes by index number, -`remove` removes on the basis of content being passed on. For instance -if :: - - k = [1,2,1,3] - del([k[2]) - -gives us [1,2,3]. :: - - k.remove(x[2]) - -will give us [2,1,3]. Since it deletes the first occurence of what is -returned by x[2] which is 1. - - - - - - - -.. #[[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 88a01948450d -r d33698326409 getting-started-with-lists/script.rst.orig --- a/getting-started-with-lists/script.rst.orig Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,224 +0,0 @@ -.. 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 88a01948450d -r d33698326409 getting-started-with-lists/slides.org --- a/getting-started-with-lists/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,100 +0,0 @@ -#+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 Lists -#+AUTHOR: FOSSEE -#+DATE: 2010-09-14 Tue -#+EMAIL: info@fossee.in - -#+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 - - 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 88a01948450d -r d33698326409 getting-started-with-lists/slides.tex --- a/getting-started-with-lists/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,149 +0,0 @@ -% Created 2010-11-10 Wed 12:22 -\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 Lists} -\author{FOSSEE} -\date{2010-09-14 Tue} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - - -\begin{frame} -\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 - \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 88a01948450d -r d33698326409 getting-started-with-symbolics/questions.rst --- a/getting-started-with-symbolics/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,61 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. How do you define a name 'y' as a symbol? - - - Answer: var('y') - -2. List out some constants pre-defined in sage? - - Answer: pi, e ,euler_gamma - -3. List the functions for differentiation and integration in sage? - - Answer: diff and integral - -4. Get the value of pi upto precision 5 digits using sage? - - Answer: n(pi,5) - -5. Find third order differential of function. - - f(x)=sin(x^2)+exp(x^3) - - Answer: diff(f(x),x,3) - -6. What is the function to find factors of an expression? - - Answer: factor - -7. What is syntax for simplifying a function f? - - Answer f.simplify_full() - -8. Find the solution for x between pi/2 to pi for the given equation? - - sin(x)==cos(x^3)+exp(x^4) - find_root(sin(x)==cos(x^3)+exp(x^4),pi/2,pi) - -9. Create a simple two dimensional matrix with two symbolic variables? - - var('a,b') - A=matrix([[a,1],[2,b]]) - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1.Find the points of intersection of the circles - - x^2 + y^2 - 4x = 1 - x^2 + y^2 - 2y = 9 - -2. Integrate the function - -x^2*cos(x) - -between 1 to 3. diff -r 88a01948450d -r d33698326409 getting-started-with-symbolics/quickref.tex --- a/getting-started-with-symbolics/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,8 +0,0 @@ -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 88a01948450d -r d33698326409 getting-started-with-symbolics/script.rst --- a/getting-started-with-symbolics/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,340 +0,0 @@ -.. Objectives -.. ---------- - -.. By the end of this tutorial, you will be able to - -.. 1. 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. - - -.. Prerequisites -.. ------------- - -.. 1. getting started with sage notebook - - -.. Author : Amit - Internal Reviewer : - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <, if OK> [2010-10-05] - -Symbolics with Sage -------------------- - -Hello friends and welcome to the tutorial on Symbolics with Sage. - -{{{ Show welcome slide }}} - -During the course of the tutorial we will learn - -{{{ Show outline slide }}} - -* 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. - -In addtion to a lot of other things, Sage can do Symbolic Math and we shall -start with defining symbolic expressions in Sage. - -Have your Sage notebook opened. If not, pause the video and -start you Sage notebook right now. - -On the sage notebook type:: - - sin(y) - -It raises a name error saying that ``y`` is not defined. We need to -declare ``y`` as a symbol. We do it using the ``var`` function. -:: - - var('y') - -Now if you type:: - - sin(y) - -Sage simply returns the expression. - -Sage treats ``sin(y)`` as a symbolic expression. We can use this to do -symbolic math using Sage's built-in constants and expressions. - -Let us try out a few examples. :: - - var('x,alpha,y,beta') - x^2/alpha^2+y^2/beta^2 - -We have defined 4 variables, ``x``, ``y``, ``alpha`` and ``beta`` and -have defined a symbolic expression using them. - -Here is an expression in ``theta`` :: - - var('theta') - sin(theta)*sin(theta)+cos(theta)*cos(theta) - -Now that you know how to define symbolic expressions in Sage, here is -an exercise. - -{{ show slide showing question 1 }} - -%% %% 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. - -The solution is on your screen. - -{{ show slide showing solution 1 }} - -Sage also provides built-in constants which are commonly used in -mathematics, for instance pi, e, infinity. The function ``n`` gives -the numerical values of all these constants. -:: - n(pi) - n(e) - n(oo) - -If you look into the documentation of function ``n`` by doing - -:: - n( - -You will see what all arguments it takes and what it returns. It will -be very helpful if you look at the documentation of all functions -introduced in the course of this script. - -Also we can define the number of digits we wish to have in the -constants. For this we have to pass an argument -- digits. Type - -:: - - n(pi, digits = 10) - -Apart from the constants Sage also has a lot of built-in functions -like ``sin``, ``cos``, ``log``, ``factorial``, ``gamma``, ``exp``, -``arcsin`` etc ... - -Lets try some of them out on the Sage notebook. -:: - - sin(pi/2) - - arctan(oo) - - log(e,e) - -Following are exercises that you must do. - -{{ show slide showing question 2 }} - -%% %% 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 - -{{ show slide showing solution 2 }} - -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('f',x) - -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. Let us define a function which is a parabola between 0 -to 1 and a constant from 1 to 2 . Type the following -:: - - - var('x') - h(x)=x^2 - g(x)=1 - - f=Piecewise([[(0,1),h(x)],[(1,2),g(x)]],x) - f - -We can also define functions convergent series and other series. - -We first define a function f(n) in the way discussed above.:: - - var('n') - function('f', n) - - -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) - - -Lets us now try another series :: - - - f(n) = (-1)^(n-1)*1/(2*n - 1) - sum(f(n), n, 1, oo) - -This series converges to pi/4. - -Following are exercises that you must do. - -{{ show slide showing question 3 }} - -%% %% 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. - -{{ show slide showing solution 3 }} - -Moving on let us see how to perform simple calculus operations using Sage - -For example lets try an expression first :: - - diff(x**2+sin(x),x) - -The diff function differentiates an expression or a function. It's -first argument is expression or function and second argument is the -independent variable. - -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 differential we need to add an extra third argument -for order :: - - diff(f(x),x,3) - -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 - -Many a times we need to find factors of an expression, we can use the -"factor" function - -:: - - y = (x^100 - x^70)*(cos(x)^2 + cos(x)^2*tan(x)^2) - f = factor(y) - -One can simplify complicated expression :: - - f.simplify_full() - -This simplifies the expression fully. We can also do simplification of -just the algebraic part and the trigonometric part :: - - f.simplify_exp() - f.simplify_trig() - -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) - -Let's 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) - -as we can see when we substitute the value the answer is almost = 0 showing -the solution we got was correct. - -Following are a few exercises 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. - - -Lets us now try some matrix algebra symbolically :: - - var('a,b,c,d') - A=matrix([[a,1,0],[0,b,0],[0,c,d]]) - A - -Now lets do some of the matrix operations on this matrix -:: - A.det() - A.inverse() - - -Following is an (are) exercise(s) that you must do. - -%% %% 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 }}} - -That brings us to the end of this tutorial. In this tutorial we learnt -how to - -* define symbolic expression and functions -* use built-in constants and functions -* use to see the documentation of a function -* do simple calculus -* substitute values in expressions using ``substitute`` function -* create symbolic matrices and perform operations on them - diff -r 88a01948450d -r d33698326409 getting-started-with-symbolics/slides.org --- a/getting-started-with-symbolics/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,160 +0,0 @@ -#+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. - -* Question 1 - - Define the following expression as symbolic - expression in sage. - - - x^2+y^2 - - y^2-4ax - -* Solution 1 -#+begin_src python - var('x,y') - x^2+y^2 - - var('a,x,y') - y^2-4*a*x -#+end_src python -* Question 2 - - Find the values of the following constants upto 6 digits precision - - - pi^2 - - euler_gamma^2 - - - - Find the value of the following. - - - sin(pi/4) - - ln(23) - -* Solution 2 -#+begin_src python - n(pi^2,digits=6) - n(sin(pi/4)) - n(log(23,e)) -#+end_src python -* Question 3 - - 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 3 -#+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 - -#+begin_src python - var('n') - f=1/(n^2-1) - sum(f(n), n, 1, oo) -#+end_src python - -* Question 4 - - Differentiate the following. - - - sin(x^3)+log(3x), to the second order - - x^5*log(x^7), to the fourth order - - - 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. - -* Solution 4 -#+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 5 - - Find the determinant and inverse of : - - A=[[x,0,1][y,1,0][z,0,y]] - -* Solution 5 -#+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. - - 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 88a01948450d -r d33698326409 getting-started-with-symbolics/slides.tex --- a/getting-started-with-symbolics/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,252 +0,0 @@ -% Created 2010-11-11 Thu 02:03 -\documentclass[presentation]{beamer} -\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\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}} - -\title{Getting started with symbolics} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\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{Question 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{Solution 1} -\label{sec-3} - -\lstset{language=Python} -\begin{lstlisting} -var('x,y') -x^2+y^2 - -var('a,x,y') -y^2-4*a*x -\end{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Question 2} -\label{sec-4} - - -\begin{itemize} -\item Find the values of the following constants upto 6 digits precision - -\begin{itemize} -\item pi$^2$ -\item euler$_{\mathrm{gamma}}$$^2$ -\end{itemize} - -\end{itemize} - -\begin{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{Solution 2} -\label{sec-5} - -\lstset{language=Python} -\begin{lstlisting} -n(pi^2,digits=6) -n(sin(pi/4)) -n(log(23,e)) -\end{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Question 3} -\label{sec-6} - -\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 3} -\label{sec-7} - -\lstset{language=Python} -\begin{lstlisting} -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{lstlisting} - -\lstset{language=Python} -\begin{lstlisting} -var('n') -f=1/(n^2-1) -sum(f(n), n, 1, oo) -\end{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Question 4} -\label{sec-8} - -\begin{itemize} -\item Differentiate the following. - -\begin{itemize} -\item sin(x$^3$)+log(3x), to the second order -\item x$^5$*log(x$^7$), to the fourth order -\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{Solution 4} -\label{sec-9} - -\lstset{language=Python} -\begin{lstlisting} -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{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Question 5} -\label{sec-10} - -\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 5} -\label{sec-11} - -\lstset{language=Python} -\begin{lstlisting} -var('x,y,z') -A=matrix([[x,0,1],[y,1,0],[z,0,y]]) -A.det() -A.inverse() -\end{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-12} - -\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. -\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-13} - - \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 88a01948450d -r d33698326409 getting_started_with_arrays/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_arrays/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,132 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. An array in Python is the same as a Python list + + a. True + #. False + +Answer: False + +2. ``x = array([1, 2, 3], [5, 6, 7])`` is a valid statement + + a. True + #. False + +Answer: False + +3. What will be the output of the following code, + :: + + x = array([[1, 2, 3], ['a', 2, 'c']]) + print x[0][0] + x[0][1] + x[0][2] + + a. 6 + #. 123 + #. a2c + #. Error as array takes only homogeneous elements + +Answer: 123 + +4. What will be the output of the following code, + :: + + x = [[1, 2, 3], [4.1, 4.2, 4.3], ['6','7',8]] + y = array(x) + print y[-1][-2] + y[-1][-1] + y[-2][0] + y[0][-2] + + a. 21.1 + #. 12.5 + #. 784.12 + #. Error as array takes only homogeneous elements + + .. 4.2 4.3 2 2 + +Answer: 784.12 + +5. What is the output of the following code, + :: + + x = array([[1, 2, 3], ['a', 2, 'c']]) + identity(x.shape) + + a. Will create an identity matrix of shape (2, 3). + #. ``identity()`` function takes an integer as argument and a tuple + is passed. + #. Will return, array([[1,0,1],[0,1,0]]) + #. Will return, array([[0,1,0],[0,1,0]]) + +Answer: ``identity()`` function takes an integer as argument and a + tuple is passed. + +6. ``ones_like()`` function? + + (A) Returns an array of ones with the same shape and type as a + given array. + (B) Return a new array of given shape and type, filled with ones. + + Read the statements and answer, + + a. Only statement A is correct. + #. Only statement B is correct. + #. Both statement A and B are correct. + #. Both statement A and B are incorrect. + +Answer: Only statement A is correct. + +7. ``zeros_like()`` function? + + (A) Return a new array of given shape and type, filled with zeros. + (B) Returns an array of zeros with the same shape and type as a + given array. + + + Read the statements and answer, + + a. Only statement A is correct. + #. Only statement B is correct. + #. Both statement A and B are correct. + #. Both statement A and B are incorrect. + +Answer: Only statement B is correct. + +8. What will be output of the following code snippet. + :: + + x = linspace(1,10,10).reshape(5,2) + print (x[-3]+x[-4]).sum() + + a. 10.0 + #. 18.0 + #. 14.0 + #. 16.44 + #. Error + +Answer: 18 + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Write a python script to create a 15x15 array of equally spaced 225 + elements from 1 to 1000, add 5 to each of the diagonal elements and + find the sum of all odd rows of the array. Say for example the + array, + :: + + x = array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + + will give answer 40 ((1+5) + 2 + 3 + 7 + 8 + (9+5)). + +2. For any given array([a1, a2, a3, .. , an]) the Vandermonde matrix + will be [[1, a1, a1**2, .. , a1**(n-1)], [1, a2, a2**2, .. , + a2**(n-1)], .. , [1, an, an**2, .. ,an**(n-1)]]. Write a python + script to generate the Vandermonde matrix and find the determinant + of the matrix for [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20]. [Hint: to find the determinant use the + function ``det()`` from ``linalg`` module.] diff -r 88a01948450d -r d33698326409 getting_started_with_arrays/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_arrays/quickref.tex Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 getting_started_with_arrays/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_arrays/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,343 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Create arrays using data +.. #. Create arrays from lists +.. #. Basic array operations +.. #. Creating identity matrix using ``identity()`` function. +.. #. Learn about ``zeros()``, ``zeros_like()``, ``ones()``, + ``ones_like()`` functions. + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` and ``pylab`` installed. +.. #. getting started with ``ipython``. +.. #. getting started with lists. + +.. Author: Anoop Jacob Thomas + Internal Reviewer : Puneeth + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <11-11-2010,Anand, OK > [2010-10-05] + +=========================== +Getting started with Arrays +=========================== + +.. #[Puneeth: Prerequisites and Objectives are missing. Fill them in] + +{{{ show the welcome slide }}} + +Welcome to the spoken tutorial on getting started with arrays. + +{{{ switch to next slide, outline slide }}} + +In this tutorial, we will learn about the data structure called an array, how to convert +a list into an array, operations on arrays and also why an array is preferred +to lists. + +.. #[Puneeth: Fix the grammar above.] + +{{{ switch to next slide on overview of array }}} + +Arrays are homogeneous data structures. Unlike lists, arrays cannot have +heterogeneous data elements, that is, they can have only one type of data +as their entries, be them all integers, strings, or maybe floats, but not a mix. + +.. #[Puneeth: Use multiple short sentences, rather than one long sentence + I would've written something like this. + + Unlike lists, arrays are homogeneous data structures. They can have only + type of data, ....] + +Arrays of a given length are comparatively much faster in mathematical +operations than lists of the same length, because of the fact that they are +homogeneous data structures. + +.. #[Puneeth: For what size of an array is that the comparison? + +{{{ switch to the next slide, creating arrays }}} + +Now let us see how to create arrays. + +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?] + +To create an array we will use the function ``array()`` as, + +:: + + a1 = array([1,2,3,4]) + +Notice that we created a one dimensional array here. Also notice the object +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 +.. concepts learnt? ] + +.. #[Puneeth: Also, you didn't even point out that we are converting a +.. list, using the ``array`` function. Bring the later section about +.. converting a list, here. A separate section is not necessary, IMHO.] + +We create two dimensional array by converting a list of lists to an array +as, + +:: + + a2 = array([[1,2,3,4],[5,6,7,8]]) + +.. #[Puneeth: Again, you could explain a bit about the fact that we are +.. converting a list of lists.] + +Now let us use ``arange()`` function to create the same array as before. + +:: + + ar = arange(1,9) + +.. #[Puneeth: say, creating the same array as before. for some time I got +.. confused .] + +And we obtained a one dimensional array with elements from 1 to 8. + +:: + + print ar + +.. #[Puneeth: be consistent with voice. say, we obtained... or something.] + +And how can we make it a two dimensional array of order 2 by 4? Pause here +and try to do it yourself, try ``ar.tab`` and find a suitable method for +that. + +{{{ switch to next slide, reshape() method }}} + +We can use the function ``reshape()`` for that purpose and it can be done +as, + +:: + + ar.reshape(2,4) + ar.reshape(4,2) + ar = ar.reshape(2,4) + +{{{ switch to next slide, creating array from list}}} + +Now, let us see how to convert a list object to an array. As you have +already seen, in both of the previous statements we have passed a list, so +creating an array can be done so, first let us create a list ``l1`` + +:: + + l1 = [1,2,3,4] + +Now we can convert the list to an array as, + +:: + + a3 = array(l1) + + +{{{ switch to the next slide, problem statement of unsolved exercise 1 }}} + +Create a three dimensional array of the shape (2,2,4). + +.. #[Puneeth: s/order/shape or size ?] + +{{{ switch to the next slide, shape of an array }}} + +To find the shape of an array we can use the method ``.shape``, let us +check the shape of the arrays we have created so far, + +.. #[Puneeth: s/object/method ?] + +:: + + a2.shape + +``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. ] + +{{{ switch to the next slide, unsolved exercise 2 }}} + +Find out the shape of the other arrays that we have created. + +.. #[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 +.. keep this, just briefly mention that arrays are homogeneous in the +.. intro, don't explain it there.] + +Now let us try to create a new array with a mix of elements and see what +will happen, + +:: + + a4 = array([1,2,3,'a string']) + +Well, we would expect an error as it has been previously mentioned that arrays handle +elements with the same datatype, but it didn't raise an error. Let us check the values +in the new array created. In your IPython terminal type, +:: + + a4 + +Did you notice it, + +{{{ switch to next slide, implicit type casting }}} + +.. #[Puneeth: typecasting may be unnecessary. (Also too advanced?) an +.. average guy wouldn't use arrays with strings.] + +.. #[Puneeth: You may want to mention that float is the default dtype.] + +{{{ highlight all the array elements one by one using mouse movements }}} + +all the elements have been implicitly type casted as strings, though our +first three elements were meant to be integers. + +.. #[Puneeth: when I type a4 it says some ``dtype`` etc. I don't understand +.. what it is, can you explain? ;)] + +{{{ switch to the next slide, identity & zeros methods }}} + +.. #[Puneeth: something needs to motivate this. why are we suddenly talking +.. of an identity matrix?] + +Now let us see how to create an identity matrix of a given size, that is a +two-dimensional array in which all the diagonal elements are ones and rest of the +elements are zeros. We can create an identity matrix using the function +``identity()``. + +The function ``identity()`` takes an integer argument which specifies the +size of the desired matrix, + +:: + + identity(3) + +As you can see the identity function returned a three by three square matrix +with all the diagonal elements as ones and the rest of the elements as zeros. + +.. #[Puneeth: You say array here, matrix there -- it's a bit messed up. +.. Clarify, explicitly.] + +``zeros()`` function accepts a tuple, which is the order of the array that we +want to create, and it generates an array with all elements as zeros. + +{{{ switch to the next slide, problem statement of solved exercise 1 }}} + +Let us creates an array of the order four by five with all the elements +zero. We can do it using the method zeros, :: + + zeros((4,5)) + +Notice that we passed a tuple to the function zeros. + +{{{ switch to next slide, learning exercise }}} + +We learned two functions ``identity()`` and ``zeros()``, find out more +about the functions ``zeros_like()``, ``ones()``, ``ones_like()``. + +{{{ switch to next slide, array operations }}} + +Try the following, first check the value of a1, +:: + + a1 + +``a1`` is a single dimensional array, and now try, +:: + + a1 * 2 + +It returned a new array with all the elements multiplied by 2. +:: + + a1 + +note that the value of a1 still remains the same. + +Similarly with addition, +:: + + a1 + 2 + +it returns a new array, with all the elements summed with two. But +again notice that the value of a1 has not been changed. +:: + + a1 + +You may change the value of a1 by simply assigning the newly returned +array as, +:: + + a1 += 2 + +Notice the change in elements of a, +:: + + a + +We can use all the mathematical operations with arrays, Now let us try this +:: + + a1 = array([1,2,3,4]) + a2 = array([1,2,3,4]) + a1 + a2 + +Returns an array with element by element addition, +:: + + a1 * a2 + +Returns an array with element by element multiplication, notice that it +does not perform matrix multiplication. + +{{{ switch to next slide, summary slide }}} + +So this brings us to the end of this tutorial, in this tutorial we covered +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] + +{{{ switch to next slide, thank you }}} + +Thank you! + +.. + Local Variables: + mode: rst + indent-tabs-mode: nil + sentence-end-double-space: nil + fill-column: 75 + End: diff -r 88a01948450d -r d33698326409 getting_started_with_arrays/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_arrays/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,135 @@ +#+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 arrays +#+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 + - Arrays + - why arrays over lists + - Creating arrays + - Array operations + +* Overview of Arrays + - Arrays are homogeneous data structures. + - elements have to the same data type + - Arrays are faster compared to lists + - at least /80-100 times/ faster than lists + +* 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]]) + 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 + : In []: ar.reshape(2, 4) + : In []: ar.reshape(4, 2) + : In []: ar = ar.reshape(2, 4) + +* Creating ~array~ from ~list~. + - ~array()~ method accepts list as argument + - Creating a list + : In []: l1 = [1, 2, 3, 4] + - Creating an array + : In []: a3 = array(l1) + +* Exercise 1 + Create a 3-dimensional array of the order (2, 2, 4). + +* ~.shape~ of array + - ~.shape~ + To find the shape of the array + : In []: a2.shape + - ~.shape~ + returns a tuple of shape +* Exercise 2 + 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']) +* Implicit type casting + : In []: a4 + All elements are type casted to string type +* ~identity()~, ~zeros()~ methods + - ~identity(n)~ + Creates an identity matrix, a square matrix of order (n, n) with diagonal elements 1 and others 0. + - ~zeros((m, n))~ + Creates an ~m X n~ matrix with all elements 0. + +* Learning exercise + - Find out about + - ~zeros_like()~ + - ~ones()~ + - ~ones_like()~ + +* Array operations + - ~a1 * 2~ + returns a new array with all elements of ~a1~ multiplied by ~2~. + - Similarly ~+~, ~-~ \& ~/~. + - ~a1 + 2~ + returns a new array with all elements of ~a1~ summed with ~2~. + - ~a1 += 2~ + adds ~2~ to all elements of array ~a1~. + - Similarly ~-=~, ~*=~ \& ~/=~. + - ~a1 + a2~ + does elements-wise addition. + - Similarly ~-~, ~*~ \& ~/~. + - ~a1 * a2~ + does element-wise multiplication + + *Note* - array(A) * array(B) does element wise multiplication and not matrix multiplication + +* Summary + In this tutorial we covered, + - Basics of arrays + - Creating arrays + - Arrays from lists + - Basic array operations + +* 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 88a01948450d -r d33698326409 getting_started_with_arrays/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_arrays/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,284 @@ +% Created 2010-11-07 Sun 15:18 +\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 arrays} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Arrays + +\begin{itemize} +\item why arrays over lists +\end{itemize} + +\item Creating arrays +\item Array operations +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Overview of Arrays} +\label{sec-2} + +\begin{itemize} +\item Arrays are homogeneous data structures. + +\begin{itemize} +\item elements have to the same data type +\end{itemize} + +\item Arrays are faster compared to lists + +\begin{itemize} +\item at least \emph{80-100 times} faster than lists +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Creating Arrays} +\label{sec-3} + +\begin{itemize} +\item Creating a 1-dimensional array +\end{itemize} + +\begin{verbatim} + 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} + +\begin{verbatim} + 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} + +\begin{verbatim} + In []: ar = arange(1,9) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{reshape()} method} +\label{sec-5} + +\begin{itemize} +\item To reshape an array +\end{itemize} + +\begin{verbatim} + In []: ar.reshape(2, 4) + In []: ar.reshape(4, 2) + In []: ar = ar.reshape(2, 4) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Creating \texttt{array} from \texttt{list}.} +\label{sec-6} + +\begin{itemize} +\item \texttt{array()} method accepts list as argument +\item Creating a list +\begin{verbatim} + In []: l1 = [1, 2, 3, 4] +\end{verbatim} + +\item Creating an array +\begin{verbatim} + In []: a3 = array(l1) +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 1} +\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-8} + +\begin{itemize} +\item \texttt{.shape} + To find the shape of the array +\begin{verbatim} + In []: a1.shape +\end{verbatim} + +\item \texttt{.shape} + returns a tuple of shape +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 2} +\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-10} + +\begin{itemize} +\item All elements in array should be of same type +\begin{verbatim} + In []: a4 = array([1,2,3,'a string']) +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Implicit type casting} +\label{sec-11} + +\begin{verbatim} + In []: a4 +\end{verbatim} + + All elements are type casted to string type +\end{frame} +\begin{frame} +\frametitle{\texttt{identity()}, \texttt{zeros()} methods} +\label{sec-12} + +\begin{itemize} +\item \texttt{identity(n)} + Creates an identity matrix, a square matrix of order (n, n) with diagonal elements 1 and others 0. +\item \texttt{zeros((m, n))} + Creates an \texttt{m X n} matrix with all elements 0. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Learning exercise} +\label{sec-13} + +\begin{itemize} +\item Find out about + +\begin{itemize} +\item \texttt{zeros\_like()} +\item \texttt{ones()} +\item \texttt{ones\_like()} +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Array operations} +\label{sec-14} + +\begin{itemize} +\item \texttt{a1 * 2} + returns a new array with all elements of \texttt{a1} multiplied by \texttt{2}. + +\begin{itemize} +\item Similarly \texttt{+}, \texttt{-} \& \texttt{/}. +\end{itemize} + +\item \texttt{a1 + 2} + returns a new array with all elements of \texttt{a1} summed with \texttt{2}. +\item \texttt{a1 += 2} + adds \texttt{2} to all elements of array \texttt{a1}. + +\begin{itemize} +\item Similarly \texttt{-=}, \texttt{*=} \& \texttt{/=}. +\end{itemize} + +\item \texttt{a1 + a2} + does elements-wise addition. + +\begin{itemize} +\item Similarly \texttt{-}, \texttt{*} \& \texttt{/}. +\end{itemize} + +\item \texttt{a1 * a2} + does element-wise multiplication +\end{itemize} + + + \textbf{Note} - array(A) * array(B) does element wise multiplication and not matrix multiplication +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-15} + + In this tutorial we covered, +\begin{itemize} +\item Basics of arrays +\item Creating arrays +\item Arrays from lists +\item Basic array operations +\end{itemize} +\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 88a01948450d -r d33698326409 getting_started_with_files/pendulum.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_files/pendulum.txt Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,90 @@ +1.0000e-01 6.9004e-01 +1.1000e-01 6.9497e-01 +1.2000e-01 7.4252e-01 +1.3000e-01 7.5360e-01 +1.4000e-01 8.3568e-01 +1.5000e-01 8.6789e-01 +1.6000e-01 8.4182e-01 +1.7000e-01 8.5379e-01 +1.8000e-01 8.5762e-01 +1.9000e-01 8.8390e-01 +2.0000e-01 8.9985e-01 +2.1000e-01 9.8436e-01 +2.2000e-01 1.0244e+00 +2.3000e-01 1.0572e+00 +2.4000e-01 9.9077e-01 +2.5000e-01 1.0058e+00 +2.6000e-01 1.0727e+00 +2.7000e-01 1.0943e+00 +2.8000e-01 1.1432e+00 +2.9000e-01 1.1045e+00 +3.0000e-01 1.1867e+00 +3.1000e-01 1.1385e+00 +3.2000e-01 1.2245e+00 +3.3000e-01 1.2406e+00 +3.4000e-01 1.2071e+00 +3.5000e-01 1.2658e+00 +3.6000e-01 1.2995e+00 +3.7000e-01 1.3142e+00 +3.8000e-01 1.2663e+00 +3.9000e-01 1.2578e+00 +4.0000e-01 1.2991e+00 +4.1000e-01 1.3058e+00 +4.2000e-01 1.3478e+00 +4.3000e-01 1.3506e+00 +4.4000e-01 1.4044e+00 +4.5000e-01 1.3948e+00 +4.6000e-01 1.3800e+00 +4.7000e-01 1.4480e+00 +4.8000e-01 1.4168e+00 +4.9000e-01 1.4719e+00 +5.0000e-01 1.4656e+00 +5.1000e-01 1.4399e+00 +5.2000e-01 1.5174e+00 +5.3000e-01 1.4988e+00 +5.4000e-01 1.4751e+00 +5.5000e-01 1.5326e+00 +5.6000e-01 1.5297e+00 +5.7000e-01 1.5372e+00 +5.8000e-01 1.6094e+00 +5.9000e-01 1.6352e+00 +6.0000e-01 1.5843e+00 +6.1000e-01 1.6643e+00 +6.2000e-01 1.5987e+00 +6.3000e-01 1.6585e+00 +6.4000e-01 1.6317e+00 +6.5000e-01 1.7074e+00 +6.6000e-01 1.6654e+00 +6.7000e-01 1.6551e+00 +6.8000e-01 1.6964e+00 +6.9000e-01 1.7143e+00 +7.0000e-01 1.7706e+00 +7.1000e-01 1.7622e+00 +7.2000e-01 1.7260e+00 +7.3000e-01 1.8089e+00 +7.4000e-01 1.7905e+00 +7.5000e-01 1.7428e+00 +7.6000e-01 1.8381e+00 +7.7000e-01 1.8182e+00 +7.8000e-01 1.7865e+00 +7.9000e-01 1.7995e+00 +8.0000e-01 1.8296e+00 +8.1000e-01 1.8625e+00 +8.2000e-01 1.8623e+00 +8.3000e-01 1.8383e+00 +8.4000e-01 1.8593e+00 +8.5000e-01 1.8944e+00 +8.6000e-01 1.9598e+00 +8.7000e-01 1.9000e+00 +8.8000e-01 1.9244e+00 +8.9000e-01 1.9397e+00 +9.0000e-01 1.9440e+00 +9.1000e-01 1.9718e+00 +9.2000e-01 1.9383e+00 +9.3000e-01 1.9555e+00 +9.4000e-01 2.0006e+00 +9.5000e-01 1.9841e+00 +9.6000e-01 2.0066e+00 +9.7000e-01 2.0493e+00 +9.8000e-01 2.0503e+00 +9.9000e-01 2.0214e+00 diff -r 88a01948450d -r d33698326409 getting_started_with_files/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_files/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,136 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here. + +1. What function is used to open a file? + + Answer: ``open`` + +#. The ``open`` function returns a + + a. string + #. list + #. file object + #. function + + Answer: file object + +#. ``open`` function opens a file by default in write mode. T or F? + + Answer: False + +#. The ``read`` method reads a file and returns the contents + + a. string + #. list + #. file object + #. None of the above + + Answer: string + +#. Given a file with ``hello.txt``, which looks like + :: + + Hello, World! + + What is the value of content, at the end of this code block:: + + f = open('hello.txt') + pre_content = f.read() + content = f.read() + f.close() + + Answer: It is a null string. + +#. The following code block prints each line of ``hello.txt``:: + + f = open('hello.txt') + for line in f.read(): + print line + + True or False? + + Answer: False + +#. Given a file with ``hello.txt``, which looks like + :: + + Hello, World! + + What is the output of :: + + f = open('hello.txt') + + for line in f: + print line + + for line in f: + print line + + f.close() + + Answer: Hello, World! is printed once. + + .. The actual answer should talk about blank lines, but I'm + .. not sure if we should get into such detail. + + .. Should this be made a multiple-choice? + + .. #[[Anoop: I think it will better if we make this multiple + choice]] + +#. Given a file with ``hello.txt``, which looks like + :: + + Hello, World! + + What is the output of :: + + f = open('hello.txt') + + for line in f: + print line + + f.close() + + for line in f: + print line + + f.close() + + Answer: Hello, World! is printed twice. + +#. Given a file with ``hello.txt``, which looks like + :: + + Hello, World! + + What is the output of :: + + f = open('hello') + + for line in f: + print line + + f.close() + + for line in f: + print line + + f.close() + + Answer: IOError - No such file or directory: 'hello' + + +Larger Questions +---------------- + +.. A minimum of 2 questions here. + +1. What does ``f.read(size)`` do? + +#. Print every alternate line of a file, starting at the first line. + +#. Print the file in reverse. Starting from the last line to the + first. diff -r 88a01948450d -r d33698326409 getting_started_with_files/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_files/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,12 @@ +\textbf{Getting Started -- files} + +\lstinline|f = open('filename')| returns a file object. \lstinline|f| +can be used to perform further operations on the file. + +\lstinline|f.read()| reads the whole file and returns the contents. + +\lstinline|f.close()| closes the file. + +\lstinline|for line in open('filename'):| -- iterate over the file +line-by-line. + diff -r 88a01948450d -r d33698326409 getting_started_with_files/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_files/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,189 @@ +.. Objectives +.. ---------- + +.. By the end of this tutorial, you will be able to +.. 1. Open and read the contents of a file. +.. #. Read files line by line. +.. #. Read all the contents of the file at once. +.. #. Close open files. + +.. Prerequisites +.. ------------- + +.. 1. getting started with ipython +.. #. getting started with lists +.. #. getting started with for + +.. Author : Puneeth + Internal Reviewer : Anoop Jacob Thomas + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <06-11-2010, Anand, OK> [2010-10-05] + +Script +------ + +{{{ Show the slide containing title }}} + +Hello Friends. Welcome to the tutorial on getting started with files. + +{{{ Show the outline for this tutorial }}} + +In this tutorial we shall learn to read files, and do some basic +actions on the file, like opening and reading a file, closing a +file, iterating through the file line-by-line, and appending the +lines of a file to a list. + +{{{ switch back to the terminal }}} + +As usual, we start IPython, using +:: + + ipython -pylab + +Let us first open the file, ``pendulum.txt`` present in +``/home/fossee/``. +:: + + f = open('/home/fossee/pendulum.txt') + +``f`` is called a file object. Let us type ``f`` on the terminal to +see what it is. +:: + + f + +The file object shows, the file which is open and the mode (read +or write) in which it is open. Notice that it is open in read only +mode, here. + +We shall first learn to read the whole file into a single +variable. Later, we shall look at reading it line-by-line. We use +the ``read`` method of ``f`` to read, all the contents of the file +into the variable ``pend``. +:: + + pend = f.read() + +Now, let us see what is in ``pend``, by typing +:: + + print pend + +We can see that ``pend`` has all the data of the file. Type just ``pend`` +to see more explicitly, what it contains. +:: + + pend + +Following is an exercise that you must do. + +{{ show slide with Question 1 }} + +%%1%% Split the variable into a list, ``pend_list``, of the lines in +the file. Hint, use the tab command to see what methods the string +variable has. + +Please, pause the video here. Do the exercise and then continue. + +{{ show slide with Solution 1 }} + +:: + + pend_list = pend.splitlines() + + pend_list + +Now, let us learn to read the file line-by-line. But, before that we +will have to close the file, since the file has already been read till +the end. + +Let us close the file opened into f. +:: + + f.close() + +Let us again type ``f`` on the prompt to see what it shows. +:: + + f + +Notice, that it now says the file has been closed. It is a good +programming practice to close any file objects that we have +opened, after their job is done. + +Let us, now move on to reading files line-by-line. + +Following is an exercise that you must do. + +%%2%% Re-open the file ``pendulum.txt`` with ``f`` as the file object. + +Please, pause the video here. Do the exercise and then continue. + +We just use the up arrow until we reach the open command and issue +it again. +:: + + f = open('/home/fossee/pendulum.txt') + +Now, to read the file line-by-line, we iterate over the file +object line-by-line, using the ``for`` command. Let us iterate over +the file line-wise and print each of the lines. +:: + + for line in f: + print line + +As we already know, ``line`` is variable, sometimes called the loop +variable, and it is not a keyword. We could have used any other +variable name, but ``line`` seems meaningful enough. + +Instead of just printing the lines, let us append them to a list, +``line_list``. We first initialize an empty list, ``line_list``. +:: + + line_list = [ ] + +Let us then read the file line-by-line and then append each of the +lines, to the list. We could, as usual close the file using +``f.close`` and re-open it. But, this time, let's leave alone the +file object ``f`` and directly open the file within the for +statement. This will save us the trouble of closing the file, each +time we open it. + +:: + + for line in open('/home/fossee/pendulum.txt'): + line_list.append(line) + +Let us see what ``line_list`` contains. +:: + + line_list + +Notice that ``line_list`` is a list of the lines in the file, along +with the newline characters. If you noticed, ``pend_list`` did not +contain the newline characters, because the string ``pend`` was +split on the newline characters. + +Using some string methods, that we shall look at in the tutorial on +strings, we can strip out the newline characters from the lines. + +.. #[[Anoop: I think the code that are required to be typed can be + added to the slide.]] + +{{{ show the summary slide }}} + +That brings us to the end of this tutorial. In this tutorial we +have learnt to open and close files, read the data in the files as +a whole, using the read command or reading it line by line by +iterating over the file object. + +{{{ 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 88a01948450d -r d33698326409 getting_started_with_files/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_files/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,73 @@ +#+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 files +#+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 + - Opening and reading contents of a file + - Closing open files + - Reading all the contents of the file at once + - Reading files line by line +* Question 1 + Split the variable into a list, =pend_list=, of the lines in the + file. Hint, use the tab command to see what methods the string + variable has. +* Solution 1 + #+begin_src python + In []: pend_list = pend.splitlines() + + In []: pend_list + #+end_src +* Question 2 + Re-open the file =pendulum.txt= with =f= as the file object. +* Solution 2 + #+begin_src python + In []: f = open('/home/fossee/pendulum.txt') + #+end_src +* Summary + - Opening a file using =open= function + - Reading all the contents of the file at once using =read()= method + - Closing open files using the =close= method + - Reading files line by line by iterating using a =for= loop +* 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 88a01948450d -r d33698326409 getting_started_with_files/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_files/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,115 @@ +% Created 2010-10-21 Thu 14:35 +\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 files} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Opening and reading contents of a file +\item Closing open files +\item Reading all the contents of the file at once +\item Reading files line by line +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Split the variable into a list, \texttt{pend\_list}, of the lines in the + file. Hint, use the tab command to see what methods the string + variable has. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-3} + +\begin{verbatim} +In []: pend_list = pend.splitlines() + +In []: pend_list +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + Re-open the file \texttt{pendulum.txt} with \texttt{f} as the file object. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} + +\begin{verbatim} +In []: f = open('/home/fossee/pendulum.txt') +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-6} + +\begin{itemize} +\item Opening a file using \texttt{open} function +\item Reading all the contents of the file at once using \texttt{read()} method +\item Closing open files using the \texttt{close} method +\item Reading files line by line by iterating using a \texttt{for} loop +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-7} + + \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 88a01948450d -r d33698326409 getting_started_with_for/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_for/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,115 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. In Python a block is represented by + + a. Curly braces + #. Begin and End keywords + #. Indentation + #. Curly braces + Indentation + #. All of the above + +Answer: Indentation + +2. Indentation is not mandatory in Python + + a. True + #. False + +Answer: False + +3. A ``for`` loop in Python, + + a. is a simple iterator + #. is a condition based loop + #. can iterate only over integer list of elements + #. All of the above + +Answer: is a simple iterator + +4. ``range()`` function can generate negative numbers + + a. True + #. False + +Answer: True + +5. ``range(a,b)`` function returns, + + a. A tuple of elements from a to b including a and b + #. A tuple of elements from a to b excluding b + #. A list of elements from a to b including a and b + #. A list of elements from a to b excluding b + +Answer: A list of elements from a to b excluding b + +6. ``linspace(1,100,2)`` and ``range(1,100,2)`` produces the same output, + + a. True + #. False + +Answer: False + +7. What is the output of the below code snippet? + :: + + y = 1 + for x in range(21): + y*=x + print y + + a. Product of natural numbers up to 20(including) + #. Product of natural numbers up to 21(including) + #. Zero + #. Error + +Answer: Zero + +8. What is the output of the below code snippet? + :: + + y = 1 + for x in range(1,21): + y*=x + print y + + a. Product of natural numbers up to 20(including) + #. Product of natural numbers up to 21(including) + #. Zero + #. Error + +Answer: Product of natural numbers up to 20(including) + +9. What is the output of the below code snippet? + :: + + y = 1 + for x in range(1,21) + y*=x + print y + + a. Product of natural numbers up to 20(including) + #. Product of natural numbers up to 21(including) + #. Zero + #. Error + +Answer: Error + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Write a python script to calculate the sum of the first 1000 + natural numbers? + +2. Write a python script to find out prime numbers up to 500. + [`hint`: a number ``A`` which is divisible by only ``1`` and ``A`` + is a prime number.] + +3. Write a python script to find out the difference between the + square of sum of first 100 natural numbers and sum of squares of + first 100 natural numbers. + diff -r 88a01948450d -r d33698326409 getting_started_with_for/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_for/quickref.tex Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 getting_started_with_for/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_for/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,308 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Write blocks of code in python. +.. #. Use for loop. +.. #. Use ``range()`` function. +.. #. Write blocks in python interpreter +.. #. Write blocks in ipython interpreter. + + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` and ``pylab`` installed. +.. #. getting started with ``ipython``. +.. #. getting started with lists. + + +.. Author : Anoop Jacob Thomas + Internal Reviewer : Nishanth + Internal Reviewer(2): Amit + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <10-11-2010, Anand, OK> [2010-10-05] + + +============================= +Getting started with for loop +============================= + +{{{ show welcome slide }}} + +Hello and welcome to the tutorial `Getting started with ``for`` loop`. + +{{{ switch to next slide, outline slide }}} + +In this tutorial we will learn about ``for`` loops in python, and also +learn how to write blocks of code in Python. + +.. #[Nishanth]: Instead of saying basics of indenting code, + say How to define code blocks in Python + +{{{ switch to next slide, about whitespaces }}} + +In Python whitespace is significant, and the blocks are visually +separated. + +.. #[nishanth]: Simply tell how blocks are defined in python. + The details like braces are not used and its + advantages like neat code can be told after completely + explaining the indentation + +.. #[Amit]: Do you want to do that here. May be its better to talk about + this after some initiation into the idea of blocks. + +The best practice is to indent the code using four spaces. + +.. #[Nishanth]: Even this detail may be skipped. Simply say use 4 spaces + for indentation. Do that while typing so that they can + actually see what is being typed. + +As you can see in the slide, ``Block B`` is an inner block and it is +indented using 4 spaces, and after ``Block B`` the next statement in +``Block A`` starts from the same indentation level of other ``Block +A`` statements. + +Now let us move straight into ``for`` loop. + +{{{ switch to next slide, problem statement of exercise 1 }}} + + +Write a for loop which iterates through a list of numbers and find the +square root of each number. +:: + + numbers are 1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916 + +.. #[nishanth]: making new list with square roots induces extra complication + like appending which has no use case here + +.. #[Nishanth]: The problem focuses more on square root and creation + of list. The problem must be simple and focusing on + nothing more but the indentation and for loop. + May be change the problem to print squares than to + print square roots. + +For the problem, first we need to create a ``list`` of numbers and +then iterate over the list and find the square root of each element in +it. And let us create a script, rather than typing it out in the +interpreter itself. Create a script called list_roots.py and type the +following. + +{{{ open the text editor and paste the following code there }}} +:: + + numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] + for each in numbers: + print "Square root of", each, "is", sqrt(each) + print "This is not in for loop!" + +.. numbers = [1, 12, 3, 4, 21, 17] + for each in numbers: + print each, each * each + +.. #[nishanth]: I don't see a use case to append the sq_root to + square_roots. It is only complicating stuff. + Simply iterate and print. + +{{{ switch to next slide, save and run script }}} + +{{{ save the script }}} + +Now save the script, and run it from your IPython interpreter. I +assume that you have started your IPython interpreter using ``-pylab`` +option. + +Run the script as, +:: + + %run -i list_roots.py + +.. #[Nishanth]: you don't have to use the -i option here + +{{{ run the script }}} + +So that was easy! All what we did was iterate over the list element by +element and then use the element for calculation. Note that here we +used two variables. One the variable ``numbers``, which is a list, +another one ``each``, which is the element of list under consideration +in each cycle of the ``for`` loop. The variable names can be chosen by +you. + +.. #[Nishanth]: The details like we didn't have to find the length + are relevant for people who have programmed in C or + other languages earlier. But for a newbie it is more + of confusing extra info. That part may be skipped. + Simply go ahead and focus on the syntax of for loop. + And how the variable name is used inside the for loop. + If you modify the question to only print, the extra + variable sq_root can also be avoided. let it be more + about "each", "numbers" and "for". no other new names. + +{{{ show the script which was created }}} + +Note that the lines after ``for`` statement, is indented using four +spaces. + +{{{ highlight the line after for statement }}} + +It means that line is part of the for loop. And it is a block of code, +although it is only a single statement in the block. And the fourth +line or the immediate line after the ``for`` block is not indented, + +{{{ highlight the fourth line - the line just after for loop }}} + +it means that it is not part of the ``for`` loop and the lines after +that doesn't fall in the scope of the ``for`` loop. Thus each block is +separated by the indentation level and that marks the importance of +white-spaces in Python. + +{{{ switch to the slide which shows the problem statement of the first +problem to be tried out }}} + +Now a question for you to try, from the given numbers make a list of +perfect squares and a list of those which are not. The numbers are, +:: + + 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}}} + +Now let us try a simple one, to print the square root of numbers in +the list. And this time let us do it right in the IPython +interpreter. + +{{{ switch to next slide, Indentation in ``ipython`` }}} + +{{{ switch focus to the IPython interpreter }}} + +So let us start with making a list. Type the following +:: + + numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] + for each in numbers: + +and now you will notice that, as soon as you press the return key +after for statement, the prompt changes to four dots and the cursor is +not right after the four dots but there are four spaces from the +dots. Please note that IPython automatically indents the block. The +four dots tell you that you are inside a block. Now type the rest of +the ``for`` loop, + +{{{ switch to next slide, Indentation in ``ipython`` (cont'd) }}} + +.. #[Nishanth]: Tell that IPython does auto indentation. + +:: + + print "Square root of", each, + print "is", sqrt(each) + +Now we have finished the statements in the block, and still the +interpreter is showing four dots, this means that you are still inside the +block. To exit from the block press the return key or the enter key twice +without entering anything else. It printed the square root of each +number in the list, and that is executed in a ``for`` loop. + +{{{ switch to next slide, Indentation in ``python`` interpreter }}} + +Now, let us find the cube of all the numbers from one to ten. But this +time let us try it in the vanilla version of Python interpreter. + +Start the vanilla version of Python interpreter by issuing the command +``python`` in your terminal. + +{{{ open the python interpreter in the terminal using the command +python to start the vanilla Python interpreter }}} + +{{{ switch to next slide, Indentation in ``python`` interpreter +(cont'd) }}} + +Start with, +:: + + for i in range(1,11): + +and press enter once, and we will see that this time it shows four +dots, but the cursor is close to the dots, so we have to indent the +block. The vanilla version of Python interpreter does not indent the +code automatically. So enter four spaces there and then type the +following +:: + + print i, "cube is", i**3 + +Now when we hit enter, we still see the four dots, to get out of the +block, hit enter once again + +.. #[Nishanth]: Here also the overhead on print can be reduced. + Think of a simple print statement. This statement + will be confusing for a newbie. + We can focus more on indentation in python. + +.. #[nishanth]: Not sure if you must use range here. You can + define a list of numbers and iterate on it. + Then say this list can also be generated using + the range function and hence introduce range. + +{{{ switch to the next slide, ``range()`` function }}} + +Okay! so the main thing that we learned here is how to use Python +interpreter and IPython interpreter to specify blocks. But while we +were generating the multiplication table we used something new, +``range()`` function. ``range()`` is an inbuilt function in Python +which can be used to generate a ``list`` of integers from a starting +number to an ending number. Note that the ending number that you +specify will not be included in the ``list``. + +.. #[Nishanth]: Show some examples of range without the step argument + May be give an exercise with negative numbers as arguments + +{{{ switch to next slide, problem statement of the next problem in +solved exercises }}} + +Now, let us print all the odd numbers from 1 to 50. Pause here and try +to solve the problem yourself. + +Let us do it in our IPython interpreter for ease of use. + +{{{ switch focus to ipython interpreter }}} + +The problem can be solved by just using the ``range()`` function. + +It can be solved as, +:: + + print range(1,51,2) + +This time we passed three parameters to ``range()`` function unlike +the previous case where we passed only two parameters. The first two +parameters are the same in both the cases. The first parameter is the +starting number of the sequence and the second parameter is the end of +the range. Note that the sequence doesn't include the ending +number. The third parameter is for stepping through the sequence. Here +we gave two which means we are skipping every alternate element. + +{{{ switch to next slide, summary slide }}} + +Thus we come to the end of this tutorial. We learned about blocks in +Python, indentation, blocks in IPython, for loop, iterating over a +list and then the ``range()`` function. + +.. #[Amit]: There does seem to too much overhead of details. Should + the first example be done using script is it necessary. + Do add some things in evolutionary manner. Like introducing + range as a list and doing a very very simple for loop.Like + iterating over [1,2,3] .Before getting into a problem. + And club details about problem in one paragraph and syntactic details + in other. + +{{{ switch to next slide, thank you slide }}} + +Thank you! diff -r 88a01948450d -r d33698326409 getting_started_with_for/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_for/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,146 @@ +#+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 for +#+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 + - ~for~ loop in Python. + - Blocks of code in Python. + - Indentation +* Whitespace in Python + - Whitespace is significant + - blocks are visually separated + - Blocks are indented using 4 spaces + : Block A + : Block A + : Block B + : Block B + : Block A + ~Block B~ is an inner block and is indented using 4 spaces +* Exercise 1 + Write a ~for~ loop which iterates through a list of numbers and find + the square root of each number. + : + The numbers are, + : 1369, 7225, 3364, 7056, 5625, 729, 7056, + : 576, 2916 +* Solution 1 + - Open text editor and type the following code + #+begin_src python + numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, + 576, 2916] + + for each in numbers: + print "Square root of", each, "is", sqrt(each) + + print "This is not in for loop!" + #+end_src +* Save \& run script + - Save the script as ~list_roots.py~ + - Run in ~ipython~ interpreter as, + : In []: %run -i list_roots.py +* Exercise 2 + From the given numbers make a list of perfect squares and a list of those which are not. + : + The numbers are, + : 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, + : 7056, 576, 2916 +* Exercise 3 (indentation in ~ipython~) + Print the square root of numbers in the list. + : + Numbers are, + : 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, + : 7056, 576, 2916 +* Indentation in ~ipython~ + : In []: numbers = [1369, 7225, 3364, 7056, 5625, + : ...: 729, 7056, 576, 2916] + + : In []: for each in numbers: + : ...: + Note the four spaces here + : + : + : + : + : + : +* Indentation in ~ipython~ (cont'd) + : In []: numbers = [1369, 7225, 3364, 7056, 5625, + : ...: 729, 7056, 576, 2916] + : In []: for each in numbers: + : ...: + Note the four spaces here + : + Now type the rest of the code + : ...: print "Square root of", each, + : ...: print "is", sqrt(each) + : ...: + : ...: +* Indentation in ~python~ interpreter + Find out the cube of all the numbers from 1 to 10. + : + /do it in the python interpreter/ +* Indentation in ~python~ interpreter (cont'd) + #+begin_src python + >>> for i in range(1, 11): + ... print i, "cube is", i**3 + ... + #+end_src +* ~range()~ function + - in built function in Python + - generates a list of integers + - /syntax:/ range([start,] stop[, step]) + - /example:/ + - range(1, 20) - /generates integers from 1 to 20/ + - range(20) - /generates integers from 0 to 20/ +* Exercise 4 + Print all the odd numbers from 1 to 50. +* Summary + - blocks in ~python~ + - indentation + - blocks in ~ipython~ interpreter + - ~for~ loop + - iterating over list using ~for~ loop + - ~range()~ function +* 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 88a01948450d -r d33698326409 getting_started_with_for/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_for/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,285 @@ +% Created 2010-10-12 Tue 12:55 +\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 for} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item \texttt{for} loop in Python. +\item Blocks of code in Python. + +\begin{itemize} +\item Indentation +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Whitespace in Python} +\label{sec-2} + +\begin{itemize} +\item Whitespace is significant + +\begin{itemize} +\item blocks are visually separated +\end{itemize} + +\item Blocks are indented using 4 spaces +\begin{verbatim} + Block A + Block A + Block B + Block B + Block A +\end{verbatim} + + \texttt{Block B} is an inner block and is indented using 4 spaces +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 1} +\label{sec-3} + + Write a \texttt{for} loop which iterates through a list of numbers and find + the square root of each number. +\begin{verbatim} + +\end{verbatim} + + The numbers are, +\begin{verbatim} + 1369, 7225, 3364, 7056, 5625, 729, 7056, + 576, 2916 +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-4} + +\begin{itemize} +\item Open text editor and type the following code +\end{itemize} + +\begin{verbatim} +numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, + 576, 2916] + +for each in numbers: + print "Square root of", each, "is", sqrt(each) + +print "This is not in for loop!" +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Save \& run script} +\label{sec-5} + +\begin{itemize} +\item Save the script as \texttt{list\_roots.py} +\item Run in \texttt{ipython} interpreter as, +\begin{verbatim} + In []: %run -i list_roots.py +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 2} +\label{sec-6} + + From the given numbers make a list of perfect squares and a list of those which are not. +\begin{verbatim} + +\end{verbatim} + + The numbers are, +\begin{verbatim} + 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, + 7056, 576, 2916 +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 3 (indentation in \texttt{ipython})} +\label{sec-7} + + Print the square root of numbers in the list. +\begin{verbatim} + +\end{verbatim} + + Numbers are, +\begin{verbatim} + 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, + 7056, 576, 2916 +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Indentation in \texttt{ipython}} +\label{sec-8} + +\begin{verbatim} + In []: numbers = [1369, 7225, 3364, 7056, 5625, + ...: 729, 7056, 576, 2916] +\end{verbatim} + + +\begin{verbatim} + In []: for each in numbers: + ...: +\end{verbatim} + + Note the four spaces here +\begin{verbatim} + + + + + + +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Indentation in \texttt{ipython} (cont'd)} +\label{sec-9} + +\begin{verbatim} + In []: numbers = [1369, 7225, 3364, 7056, 5625, + ...: 729, 7056, 576, 2916] + In []: for each in numbers: + ...: +\end{verbatim} + + Note the four spaces here +\begin{verbatim} + +\end{verbatim} + + Now type the rest of the code +\begin{verbatim} + ...: print "Square root of", each, + ...: print "is", sqrt(each) + ...: + ...: +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Indentation in \texttt{python} interpreter} +\label{sec-10} + + Find out the cube of all the numbers from 1 to 10. +\begin{verbatim} + +\end{verbatim} + + \emph{do it in the python interpreter} +\end{frame} +\begin{frame}[fragile] +\frametitle{Indentation in \texttt{python} interpreter (cont'd)} +\label{sec-11} + +\begin{verbatim} +>>> for i in range(1, 11): +... print i, "cube is", i**3 +... +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{\texttt{range()} function} +\label{sec-12} + +\begin{itemize} +\item in built function in Python +\item generates a list of integers + +\begin{itemize} +\item \emph{syntax:} range([start,] stop[, step]) +\item \emph{example:} + +\begin{itemize} +\item range(1, 20) - \emph{generates integers from 1 to 20} +\item range(20) - \emph{generates integers from 0 to 20} +\end{itemize} + +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 4} +\label{sec-13} + + Print all the odd numbers from 1 to 50. +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-14} + +\begin{itemize} +\item blocks in \texttt{python} +\item indentation +\item blocks in \texttt{ipython} interpreter +\item \texttt{for} loop +\item iterating over list using \texttt{for} loop +\item \texttt{range()} function +\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 88a01948450d -r d33698326409 getting_started_with_functions/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_functions/questions.rst Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 getting_started_with_functions/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_functions/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,4 @@ +Defining a function:\\ +{\ex \lstinline| def name([arguments]):|} +{\ex \lstinline| code|} +{\ex \lstinline| [return values]|} diff -r 88a01948450d -r d33698326409 getting_started_with_functions/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_functions/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,293 @@ +.. 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 : + Language Reviewer : Bhanukiran + 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 as many times as needed. 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 4 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 and the second line is used to +fix what the function is supposed to return. ``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's 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 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 in the number n are even, +.. returns False if all the digits in the number n are 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 88a01948450d -r d33698326409 getting_started_with_functions/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_functions/slides.org Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 getting_started_with_functions/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_functions/slides.tex Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 getting_started_with_ipython/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_ipython/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,186 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. ``ipython`` is a programming language similar to Python. T or F? + + Answer: False + +#. Which key combination quits ``ipython``? + + a. Ctrl + C + #. Ctrl + D + #. Alt + C + #. Alt + D + + Answer: Ctrl + D + +#. Which key combination raises a ``keyboard interrupt`` + + a. Ctrl + C + #. Ctrl + D + #. Alt + C + #. Alt + D + + Answer: Ctrl + C + +#. If you have typed the following commands:: + + 1 + 2 + 3 - 5 + 1 - 6 + 5 + 5 + 3 * 2 + + What is the result of the following actions. + + * up arrow 3 times + * backspace 4 times + + Answer: 1 + +#. If you have typed the following commands:: + + 1 + 2 + 3 - 5 + 1 - 6 + 5 + 5 + 3 * 2 + + What is the result of the following actions. + + * type ``1`` + * up arrow 2 times + + Answer: 1 + 2 + +#. If you have typed the following commands:: + + 1 + 2 + 3 - 5 + 1 - 6 + 5 + 5 + 3 * 2 + + What is the result of the following actions. + + * type ``5`` + * up arrow 2 times + + Answer: 5 + 5 + +#. If you have typed the following commands:: + + 1 + 2 + 3 - 5 + 1 - 6 + 5 + 5 + 3 * 2 + + What is the result of the following actions. + + * type ``1`` + * up arrow 1 time + * left arrow 3 times + * up arrow key + + Answer: 1 - 6 + +#. If you have typed the following commands:: + + 1 + 2 + 3 - 5 + 1 - 6 + 5 + 5 + 3 * 2 + + What is the result of the following actions. + + * type ``1`` + * up arrow 1 time + * left arrow 3 times + * down arrow key + + Answer: 1 - 6 + +#. If the following are only commands available in ``ipython`` + + * zebra + * zenith + * zest + + What are the commands listed by typing ``z`` and hitting the key + + Answer: zebra, zenith, zest + +#. If the following are only commands available in ``ipython`` + + * zebra + * zenith + * zest + + ``z`` is auto-completed to ``ze`` by hitting the key after typing + ``z``. T or F? + + Answer: True + + +#. If the following are only commands available in ``ipython`` + + * zebra + * zenith + * zest + + What are the commands listed by typing ``zeb`` and hitting the key + + Answer: zebra + +#. If the following are only commands available in ``ipython`` + + * zebra + * zenith + * zest + + What are the commands listed by typing ``z`` and hitting the key + + Answer: zebra, zenith, zest + +#. Which character is used at the end of a command, in ``ipython`` to display + the documentation. + + a. _ + #. ? + #. ! + #. & + + Answer: ? + +#. What happens if the size of documentation text is more than that can be + accomodated on your screen. + + a. The whole documentation is printed and it is auto scrolled to bottom + #. Only a part of documentation is shown and the remaining can be scrolled + through using up and down arrows + #. Only a part of documentation is shown and cursor returns to ``In`` prompt + + Answer: Only a part of documentation is shown and the remaining can be + scrolled through using up and down arrows + +#. Which key is used to quit the documentation that runs several pages and + return to the ``ipython`` prompt. + + a. a + #. c + #. q + #. + + Answer: q + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) +..[[Anand: Long answer questions required]] +1. Question 1 +2. Question 2 diff -r 88a01948450d -r d33698326409 getting_started_with_ipython/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_ipython/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,14 @@ +\textbf{Getting started -- \texttt{ipython}} + +To start \lstinline|ipython| with \lstinline|pylab|:\\ +\lstinline| $ ipython -pylab| %$ + +To exit: \lstinline|^D| (Ctrl-D) + +To interrupt: \lstinline|^C| (Ctrl-C) + +Tab completes partial commands + +\texttt{?} to look up documentation. + +Arrow keys to navigate the history. diff -r 88a01948450d -r d33698326409 getting_started_with_ipython/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_ipython/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,235 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. invoke the ``ipython`` interpreter. +.. #. quit the ``ipython`` interpreter. +.. #. navigate in the history of ``ipython``. +.. #. use tab-completion. +.. #. look-up documentation of functions. +.. #. interrupt incomplete or incorrect commands. + +.. Prerequisites +.. ------------- + +.. should have ``ipython`` and ``pylab`` installed. + +.. Author : Puneeth + Internal Reviewer : Anoop Jacob Thomas + Language Review : Bhanukiran + External Reviewer : + Checklist OK? : [2010-10-05] + + +Script +------ + +{{{ Show the slide containing title }}} + +Hello Friends and Welcome to the tutorial on getting started with +``ipython``. + +{{{ Show slide with outline }}} + +This tutorial will cover the basic usage of the ``ipython`` +interpreter. The following topics would be covered. + +IPython is an enhanced Python interpreter that provides features like +tabcompletion, easier access to help and lot of other functionality +which are not available in the vanilla Python interpreter. + +First let us see how to invoke the ``ipython`` interpreter. + +We type +:: + + ipython + +at the terminal prompt to invoke the ipython interpreter. + +We get a prompt with ``In [1]:`` after getting some information about +the version of Python installed and some help commands. + +If you get an error saying something like ``ipython is not +installed``, refer to the tutorial on how to install the packages +required for this course. + +Now, to quit the ipython interpreter, type Ctrl-D. You are prompted +asking if you really want to exit, type y to say yes and quit ipython. + +Start ipython again, as you did before. + +The prompt that you have says ``In [1]``. ``In`` stands for input and the +ipython interpreter is ready to accept input from you. + +Now let us see, how we can type some commands into the interpreter. + +Start with the simplest thing, addition. + +Let's type +:: + 1+2 + +at the prompt. IPython promptly gives back the output as 3. Notice +that the output is displayed with an ``Out[1]`` indication. + +.. #[[Anoop: I think we can illustrate In [] and Out[] in slides]] +.. #[[Puneeth: I think we can do that on the terminal?]] + +Let's try out few other mathematical operations. +:: + + 5 - 3 + 7 - 4 + 6 * 5 + +Now let's ``print 1+2``. Instead of typing the whole thing, we make +use of the fact that IPython remembers the history of the commands +that you have already used. We use the up arrow key to go back the +command ``1+2``. We then use the left-arrow key to navigate to the +beginning of the line and add the word ``print`` and a space. Then hit +enter and observe that the interpreter prints out the value as 3, +without the Out[] indication. + +Now, let's change the previous command ``print 1+2`` to ``print +10*2``. We use the up arrow again to navigate to the previous command +and use the left arrow key to move the cursor on to the + symbol and +then use the delete key to remove it and type 0 and * to change the +expression as required. We hit enter to see the output of +``print``. + +Now, let's say we want to use the function ``round``. We type ``ro`` +at the prompt and hit the tab key. As you can see, IPython +completes the command. This feature is called the tab-completion. + +Now, we remove all the characters and just type ``r`` and then hit +tab. IPython does not complete the command since there are many +possibilities. It just lists out all the possible completions. + +Following is an exercise that you must do. + +%%1%% Type ``ab`` and hit tab to see what happens. Next, just type +``a`` and hit tab to see what happens. + +Please, pause the video here. Do the exercise and then continue. + +``ab`` tab completes to ``abs`` and ``a`` gives us a list of all +the commands starting with a. + +Now, let's see what these functions are used for. We will use the +help features of ipython to find this out. + +.. #[[Anoop: Another slide which says about ? mark and round? etc, as + few people cannot just follow by listening (like me) :)]] + +.. #[Punch: These things are shown on the terminal. I feel we don't +.. need slide, here I guess.] + +To get the help of any function, we first type the function, ``abs`` +in our case and then add a ? at the end and hit enter. + +As the documentation says, ``abs`` accepts a number as an input and +returns it's absolute value. + +We say, +:: + + abs(-19) + + abs(19) + +We get 19, as expected, in both the cases. + +Does it work for decimals (or floats)? Let's try typing abs(-10.5) +and we do get back 10.5. + +Following is an exercise that you must do. + +%%2%% Look-up the documentation of ``round`` and see how to use it. + +Please, pause the video here. Do the exercise and then continue. + +:: + + round? + +If you notice, there are extra square brackets around the ``ndigits``. +This means that ``ndigits`` is optional and 0 is the default value. +Optional parameters are shown in square brackets anywhere in Python +documentation. + +The function ``round``, rounds a number to a given precision. + +Following are exercises that you must do. + +%%3%% Check the output of:: + + round(2.48) + round(2.48, 1) + round(2.48, 2) + + round(2.484) + round(2.484, 1) + round(2.484, 2) + +Please, pause the video here. Do the exercises and then continue. + +We get 2.0, 2.5 and 2.48, which are what we expect. + +Let's now see how to correct typing errors that we make while typing at +the terminal. As already shown, if we haven't hit the enter key +already, we could navigate using the arrow keys and make deletions +using delete or backspace key and correct the errors. + +Let's now type round(2.484 and hit enter, without closing the +parenthesis. We get a prompt with dots. This prompt is the +continuation prompt of ``ipython``. It appears, the previous line is +incomplete in some way. We now complete the command by typing, the +closing parenthesis and hitting enter. We get the expected output of +2.5. + +In other instances, if we commit a typing error with a longer and more +complex expression and end up with the continuation prompt, we can +type Ctrl-C to interrupt the command and get back the ``ipython`` input +prompt. + +Following is an exercise that you must do. + +%%4%% Try typing round(2.484, and hit enter. and then cancel the +command using Ctrl-C. Then, type the command, round(2.484, 2) and +resume the video. + +Please, pause the video here. Do the exercises and then continue. + +:: + + round(2.484 + ^C + + round(2.484, 2) + +This brings us to the end of the tutorial on getting started with +``ipython``. + +.. #[[Anoop: add slides for interrupts, navigating history, I feel + even a single point will also do]] + +.. #[Puneeth: I don't feel these things cannot be shown on a slide.] + +In this tutorial we have learnt, how to +{{{ show the outline/summary slide. }}} + + 1. invoke the ``ipython`` interpreter. + #. quit the ``ipython`` interpreter. + #. navigate in the history of ``ipython``. + #. use tab-completion. + #. look-up documentation of functions. + #. interrupt incomplete or incorrect commands. + +{{{ 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 88a01948450d -r d33698326409 getting_started_with_ipython/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_ipython/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,99 @@ +#+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 -- ~ipython~ +#+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 + + invoke the ~ipython~ interpreter + + quit the ~ipython~ interpreter + + navigate in the history of ~ipython~ + + use tab-completion + + look-up documentation of functions + + interrupt incomplete or incorrect commands +* Question 1 + Type =ab= and hit tab to see what happens. Next, just type =a= and + hit tab to see what happens. +* Solution 1 + =ab= tab completes to =abs= and =a= gives us a list of all the + commands starting with a. +* Question 2 + Look-up the documentation of =round= and see how to use it. +* Solution 2 + =round?= +* Question 3 + Check the output of + #+begin_src python + round(2.48) + round(2.48, 1) + round(2.48, 2) + + round(2.484) + round(2.484, 1) + round(2.484, 2) + #+end_src + Look-up the documentation of =round= and see how to use it. +* Solution 3 + We get 2.0, 2.5 and 2.48, which are what we expect. +* Question 4 + Try typing =round(2.484=, and hit enter. and then cancel the command + using Ctrl-C. Then, type the command, =round(2.484, 2)= and resume + the video. +* Solution 4 + #+begin_src python + round(2.484 + ^C + + round(2.484, 2) + #+end_src + + + +* Summary + + invoking and quitting the ~ipython~ interpreter + + navigating the history + + using tab-completion to work faster + + looking-up documentation using ~?~ + + sending keyboard interrupts using ~Ctrl-C~ + +* 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 88a01948450d -r d33698326409 getting_started_with_ipython/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_ipython/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,154 @@ +% Created 2010-11-05 Fri 20:59 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\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}} + +\title{Getting Started -- \texttt{ipython}} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item invoke the \texttt{ipython} interpreter +\item quit the \texttt{ipython} interpreter +\item navigate in the history of \texttt{ipython} +\item use tab-completion +\item look-up documentation of functions +\item interrupt incomplete or incorrect commands +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Type \texttt{ab} and hit tab to see what happens. Next, just type \texttt{a} and + hit tab to see what happens. +\end{frame} +\begin{frame} +\frametitle{Solution 1} +\label{sec-3} + + \texttt{ab} tab completes to \texttt{abs} and \texttt{a} gives us a list of all the + commands starting with a. +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + Look-up the documentation of \texttt{round} and see how to use it. +\end{frame} +\begin{frame} +\frametitle{Solution 2} +\label{sec-5} + + \texttt{round?} +\end{frame} +\begin{frame}[fragile] +\frametitle{Question 3} +\label{sec-6} + + Check the output of +\lstset{language=Python} +\begin{lstlisting} +round(2.48) +round(2.48, 1) +round(2.48, 2) + +round(2.484) +round(2.484, 1) +round(2.484, 2) +\end{lstlisting} + Look-up the documentation of \texttt{round} and see how to use it. +\end{frame} +\begin{frame} +\frametitle{Solution 3} +\label{sec-7} + + We get 2.0, 2.5 and 2.48, which are what we expect. +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-8} + + Try typing \texttt{round(2.484}, and hit enter. and then cancel the command + using Ctrl-C. Then, type the command, \texttt{round(2.484, 2)} and resume + the video. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 4} +\label{sec-9} + +\lstset{language=Python} +\begin{lstlisting} +round(2.484 +^C + +round(2.484, 2) +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-10} + +\begin{itemize} +\item invoking and quitting the \texttt{ipython} interpreter +\item navigating the history +\item using tab-completion to work faster +\item looking-up documentation using \texttt{?} +\item sending keyboard interrupts using \texttt{Ctrl-C} +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-11} + + \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 88a01948450d -r d33698326409 getting_started_with_lists/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_lists/questions.rst Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 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 Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 getting_started_with_lists/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_lists/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,19 @@ +Creating an list\\ +{\ex \lstinline| empty=[]|} + +Create a filled list\\ +{\ex \lstinline| nonempty = ['spam', 'eggs', 100, 1.234] |} + +Accessing a list\\ +{\ex \lstinline| nonempty[0] |} +{\ex \lstinline| nonempty[-1] |} + +Length of a list\\ +{\ex \lstinline| len(nonempty) |} + +Append an element to a list\\ +{\ex \lstinline| nonempty.append('python') |} + +Remove elements of a list\\ +{\ex \lstinline| del(nonempty[1] |} +{\ex \lstinline| nonempty.remove(100) |} diff -r 88a01948450d -r d33698326409 getting_started_with_lists/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_lists/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,242 @@ +.. 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 : + Language Reviewer : Bhanukiran + Checklist OK? : <12-11-2010, Anand, 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 mutually +different datatypes. List is also a sequence data type, all the +elements are arranged in a given order. + +.. #[[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 (or items) between two square brackets. + +As we can see lists can contain different kinds of data. In the +previous example 'spam' and 'eggs' are strings whereas 100 and 1.234 are +integer and float respectively. Thus we can put elements of different types in +lists including lists itself. This property makes lists heterogeneous +data structures. + +.. #[[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 an element of a list using its corresponding index. Index of +the first element of a list is 0. So for the 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 the last which, in this case, is the first element. + +We can append elements to the end of a list using the method append. :: + + 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 nonempty is appended with 'onemore' and 6 at the end. + +Using len function we can check the number of elements in the list +nonempty. In this case it is 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, 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 +would 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 +and therefore `remove` removes the first occurence of the element in the sequence +and leaves others untouched. + +One should remember this that while del removes by index number, +`remove` removes on the basis of content being passed on. For instance +if :: + + k = [1,2,1,3] + del([k[2]) + +gives us [1,2,3]. :: + + k.remove(x[2]) + +will give us [2,1,3]. Since it deletes the first occurence of what is +returned by x[2] which is 1. + + + + + + + +.. #[[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 88a01948450d -r d33698326409 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 Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 getting_started_with_lists/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_lists/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,100 @@ +#+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 Lists +#+AUTHOR: FOSSEE +#+DATE: 2010-09-14 Tue +#+EMAIL: info@fossee.in + +#+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 + - 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 88a01948450d -r d33698326409 getting_started_with_lists/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_lists/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,149 @@ +% Created 2010-11-10 Wed 12:22 +\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 Lists} +\author{FOSSEE} +\date{2010-09-14 Tue} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + + +\begin{frame} +\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 + \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 88a01948450d -r d33698326409 getting_started_with_sage_notebook/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_sage_notebook/questions.rst Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 getting_started_with_sage_notebook/quickref.tex diff -r 88a01948450d -r d33698326409 getting_started_with_sage_notebook/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_sage_notebook/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,325 @@ +.. Objectives +.. ---------- + +.. Clearly state the objectives of the LO (along with RBT level) + +.. By the end of this tutorial, you should -- + +.. #. Know what Sage and Sage notebook are. +.. #. Be able to start a Sage shell or notebook +.. #. Be able to start using the notebook +.. #. Be able to create new worksheets +.. #. Know about the menu options available +.. #. Know about the cells in the worksheet +.. #. Be able to evaluate cells, create and delete cells, navigate them. +.. #. Be able to make annotations in the worksheet +.. #. Be able to use tab completion. +.. #. Be able to use code from other languages in the cells. + +.. Prerequisites +.. ------------- + +.. None. + +.. Author : Madhu + Internal Reviewer : Punch + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <15-11-2010, Anand, OK> [2010-10-05] + + +Script +------ + +{{{ Show the slide containing the title }}} + +Hello friends. Welcome to this spoken tutorial on Getting started with +Sage and Sage notebook. + +{{{ Show the slide containing the outline }}} + +In this tutorial, we will learn what Sage is, what is Sage notebook, +how to start and use the sage notebook. In the notebook we will be +specifically learning how to execute our code, how to write +annotations and other content, typesetting the content and how to use +the offline help available. + +{{{ Show the slide on what is Sage }}} + +To start with, What is Sage? Sage is a free, open-source mathematical +software. Sage can do a lot of math stuff for you including, but not +limited to, algebra, calculus, geometry, cryptography, graph theory +among other things. It can also be used as aid in teaching and +research in any of the areas that Sage supports. So let us start Sage +now + +{{{ Shift to terminal }}} + +We are assuming that you have Sage installed on your computer now. If +not please visit the page +http://sagemath.org/doc/tutorial/introduction.html#installation for +the tutorial on how to install Sage. + + +Let us now learn how to start Sage. On the terminal type:: + + sage + +This should start a new Sage shell with the prompt sage: which looks +like this + +{{{ Show what is displayed on the terminal }}} + +So now we can type all the commands that Sage supports here. But Sage +comes bundled with a much more elegant tool called Sage +Notebook? What is Sage Notebook? Sage Notebook provides a web based +user interface to use Sage. So once we have a Sage notebook server up +and running, all we want is a browser to access the Sage +functionality. For example there is an official instance of Sage +Notebook server running at http://sagenb.org You can visit that page, +create an account there and start using Sage! So all you need is just +a browser, a modern browser + +{{{ Intentional *cough* *cough* }}} + +#[[Bhanu: what? Are you serious?]] + +to use Sage and nothing else! The Sage notebook also provides a +convenient way of sharing and publishing our work, which is very handy +for research and teaching. + +However we can also run our own instances of Sage notebook servers on +all the computers we have a local installation of Sage. To start the +notebook server just type:: + + notebook() + +on the Sage prompt. This will start the Sage Notebook server. If we +are starting the notebook server for the first time, we are prompted +to enter the password for the admin. Type the password and make a note +of it. After this Sage automatically starts a browser page for you +with the notebook opened. + +If it doesn't automatically start a browser page check if the Notebook +server started and there were no problems. If so open your browser and +in the address bar type the URL shown in the instructions upon running +the notebook command on the sage prompt. + +{{{ The notebook() command gives an instruction telling +Open your web browser to http://localhost:8000. Point towards it }}} + +In our case it is http://localhost:{{{ Tell whatever is shown }}} + +{{{ Show the browser with Sage notebook }}} + +If you are not logged in yet, it shows the Notebook home page and +textboxes to type the username and the password. You can use the +username 'admin' and the password you gave while starting the notebook +server for the first time. There are also links to recover forgotten +password and to create new accounts. + +{{{ If you are logged in tell that you are logged in, log out and show +what is said above for the login page }}} + +Once we are logged in with the admin account we can see the notebook +admin page. A notebook can contain a collection of Sage Notebook +worksheets. Worksheet is basically a working area. This is where +we enter all the Sage commands on the notebook. + +The admin page lists all the worksheets created. On the topmost part +of this page we have the links to various pages. + +{{{ Whenever you talk on an individual link point your mouse towards +the link. For each of the link go to the page and explain as below }}} + +The home link takes us to the admin home page. The published link +takes us to the page which lists all the published worksheets. The log +link has the complete log of all the actions we did on the +notebook. We have the settings link where we can configure our notebook, +the notebook server, create and mangage accounts. We have a +link to help upon clicking opens a new window with the complete help +of Sage. The entire documentation of Sage is supplied with Sage for +offline reference and this help link is the way to get into it. Then +we can report bugs about Sage by clicking on Report a Problem link and +there is a link to sign out of the notebook. + +We can create a new worksheet by clicking New Worksheet link + +{{{ Click on the link }}} + +Sage prompts you for a name for the worksheet. Let us name the +worksheet as nbtutorial. Now we have our first worksheet which is +empty. + +A worksheet will contain a collection of cells. Every Sage command +must be entered in this cell. Cell is equivalent to the prompt on +console. When we create a new worksheet, to start with we will have +one empty cell. Let us try out some math here:: + + 2 + 2 + 57.1 ^ 100 + +The cap operator is used for exponentiation. If you observed carefully +we typed two commands but the output of only last command was +displayed. By default each cell displays the result of only the last +operation. We have to use print statement to display all the results +we want to be displayed. + +{{{ Demonstrate creating a new cell }}} + +Now to perform more operations we want more cells. So how do we create +a new cell? It is very simple. As we hover our mouse above or below +the existing cells we see a blue line, by clicking on this new line we +can create a new cell. + +We have a cell, we have typed some commands in it, but how do we +evaluate that cell? Pressing Shift along with Enter evaluates the +cell. Alternatively we can also click on the evaluate link to evaluate +the cell + +{{{ Evaluate the cell and demonstrate for both methods separately +}}}:: + + matrix([[1,2], [3,4]])^(-1) + +After we create many cells, we may want to move between the cells. To +move between the cells use Up and Down arrow keys. Also clicking on +the cell will let you edit that particular cell. + +{{{ Move between two cells created }}} + +To delete a cell, clear the contents of the cell and hit backspace + +{{{ Clear and demonstrate deleting the cell }}}:: + + Makes no sense + +If you want to add annotations in the worksheet itself on the blue +line that appears on hovering the mouse around the cell, Hold Shift +and click on the line. This creates a What You See Is What You Get +cell. + +{{{ Create a HTML editable cell }}} + +We can make our text here rich text. We can make it bold, Italics, we +can create bulleted and enumerated lists in this area:: + + This text contains both the **bold** text and also *italicised* + text. + It also contains bulleted list: + * Item 1 + * Item 2 + It also contains enumerate list: + 1. Item 1 + 2. Item 2 + +In the same cell we can display typeset math using the LaTeX like +syntax:: + + $\int_0^\infty e^{-x} \, dx$ + +We enclose the math to be typeset within $ and $ or $$ and $$ as in +LaTeX. + +We can also obtain help for a particular Sage command or function +within the worksheet itself by using a question mark following the +command:: + + sin? + +Evaluating this cell gives me the entire help for the sin function +inline on the worksheet itself. Similarly we can also look at the +source code of each command or function using double question mark:: + + matrix?? + +Sage notebook also provides the feature for autocompletion. To +autocomplete a command type first few unique characters and hit tab +key:: + + sudo + +To see all the commands starting with a specific name type those +characters and hit tab:: + + plo + +To list all the methods that are available for a certain variable or +a datatype we can use the variable name followed by the dot to access +the methods available on it and then hit tab:: + + s = 'Hello' + s.rep + +The output produced by each cell can be one of the three states. It +can be either the full output, or truncated output or hidden output. +The output area will display the error if the Sage code we wrote in +the cell did not successfully execute:: + + a, b = 10 + +{{{ Show the three states }}} + +The default output we obtained now is a truncated output. Clicking at +the left of the output area when the mouse pointer turns to hand gives +us the full output, clicking again makes the output hidden and it +cycles. + +Lastly, Sage supports a variety of languages and each cell on the +worksheet can contain code written in a specific language. It is +possible to instruct Sage to interpret the code in the language we +have written. This can be done by putting percentage sign(%) followed +by the name of the language. For example, to interpret the cell as +Python code we put:: + + %python + +as the first line in the cell. Similarly we have: %sh for shell +scripting, %fortran for Fortran, %gap for GAP and so on. Let us see +how this works. Say I have an integer. The type of the integer in +default Sage mode is +{{{ Read the output }}}:: + + a = 1 + type(a) + + Output: + +We see that Integers are Sage Integers. Now let us put %python as the +first line of the cell and execute the same code snippet:: + + %python + a = 1 + type(a) + + Output: + +Now we see that the integer is a Python integer. Why? Because now we +instructed Sage to interpret that cell as Python code. + +This brings us to the end of the tutorial on using Sage. We learnt +quite a lot about using the Notebook User Interface of Sage. We are +now confident that we can comfortably use the notebook to learn more +about Sage in the following tutorials. Let us summarize what we +learnt. In this session we learnt + + * What is Sage + * How to start Sage shell + * What is Sage notebook + * How to start the Sage notebook + * How to create accounts and start using the notebook + * How to create new worksheets + * The menus available on the notebook + * About cells in the worksheet + * Methods to evaluate the cell, create new cells, delete the cells + and navigate around the cells + * To make annotations in the worksheet + * Tab completions + * And embedding code of other scripting languages in the cells + +{{{ 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 88a01948450d -r d33698326409 getting_started_with_sage_notebook/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_sage_notebook/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,80 @@ +#+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 -- Sage +#+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 + - Know what Sage and Sage notebook are. + - Be able to start a Sage shell or notebook + - Be able to start using the notebook + - Be able to create new worksheets + - Know about the menu options available + - Know about the cells in the worksheet + - Be able to evaluate cells, create and delete cells, navigate them. + - Be able to make annotations in the worksheet + - Be able to use tab completion. + - Be able to use code from other languages in the cells. +* What is Sage? + - free, open-source mathematical software. + - can do a lot of math for you, including, but not limited to + + algebra + + geometry + + cryptography + + graph theory + - can be used as aid in teaching and research +* Summary + + What is Sage + + How to start Sage shell + + What is Sage notebook + + How to start the Sage notebook + + How to create accounts and start using the notebook + + How to create new worksheets + + The menus available on the notebook + + About cells in the worksheet + + Methods to evaluate the cell, create new cells, delete the cells + and navigate around the cells + + To make annotations in the worksheet + + Tab completions + + And embedding code of other scripting languages in the cells +* 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 88a01948450d -r d33698326409 getting_started_with_sage_notebook/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_sage_notebook/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,115 @@ +% Created 2010-11-11 Thu 02:40 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\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}} + +\title{Getting started -- Sage} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Know what Sage and Sage notebook are. +\item Be able to start a Sage shell or notebook +\item Be able to start using the notebook +\item Be able to create new worksheets +\item Know about the menu options available +\item Know about the cells in the worksheet +\item Be able to evaluate cells, create and delete cells, navigate them. +\item Be able to make annotations in the worksheet +\item Be able to use tab completion. +\item Be able to use code from other languages in the cells. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{What is Sage?} +\label{sec-2} + +\begin{itemize} +\item free, open-source mathematical software. +\item can do a lot of math for you, including, but not limited to + +\begin{itemize} +\item algebra +\item geometry +\item cryptography +\item graph theory +\end{itemize} + +\item can be used as aid in teaching and research +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-3} + +\begin{itemize} +\item What is Sage +\item How to start Sage shell +\item What is Sage notebook +\item How to start the Sage notebook +\item How to create accounts and start using the notebook +\item How to create new worksheets +\item The menus available on the notebook +\item About cells in the worksheet +\item Methods to evaluate the cell, create new cells, delete the cells + and navigate around the cells +\item To make annotations in the worksheet +\item Tab completions +\item And embedding code of other scripting languages in the cells +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-4} + + \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 88a01948450d -r d33698326409 getting_started_with_strings/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_strings/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,80 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. List the type of quotes that can be used to define strings. + + Answer: 'single quotes', "double quotes", + '''triple single quotes''' + """triple double quotes""" + +#. Given the strings ``s`` and ``S``, ``s='Hello World'`` and + ``S="Hello World``. s and S are different strings. True or False? + +#. What is the output of:: + + s = 'It's all here' + + Answer: ``SyntaxError`` + +#. Write code to assign s, the string ``' is called the apostrophe`` + + Answer: ``s = "`is called the apostrophe"`` + +#. Given strings s and t, ``s = "Hello"`` and ``t = "World"``. What is + the output of s + t? + + Answer: HelloWorld + +#. Given strings s and t, ``s = "Hello"`` and ``t = "World"`` and an + integer r, ``r = 2``. What is the output of s * r + s * t? + + Answer: HelloHelloWorldWorld + +#. Given strings s and t, ``s = "Hello"`` and ``t = "World"`` and an + integer r, ``r = 2``. What is the output of s * 'r' ? + + Answer: TypeError - can't multiply a sequence by non-int + +#. Given the string ``s = "Hello"``, we wish to change it to + ``hello``. what is the result of:: + + s[0] = 'h' + + Answer: TypeError - 'str' object does not support item assignment. + +#. Given the string ``s = "Hello"``, we wish to change it to + ``hello``. what is the result of:: + + s = "hello" + + Answer: s is changed to "hello" + +#. Which type of string can be written in multiple lines, with line + breaks. (Note: more than one answer may be correct.) + + #. triple double quoted strings + #. single quoted strings + #. double quoted strings + #. triple single quoted strings + + Answer: triple double quoted strings and triple single quoted strings + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Given the string s, ``s = F.R.I.E.N.D.S``, obtain the string + "FRIENDS". + + Answer:: + + s = s[0] + s[2] + s[4] + s[6] + s[8] + s[10] + s[12] + +2. Assign the string ``Today's Quote: "Don't believe in any quote, + including this."`` to the variable ``quote``. + + Answer: + quote = """Today's Quote: "Don't believe in any quote, including this.""" diff -r 88a01948450d -r d33698326409 getting_started_with_strings/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_strings/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,8 @@ +Creating a string:\\ +{\ex \lstinline| s = ``Hello World''|} -- Single quotes and triple +quotes can also be used. + +Accessing individual elements:\\ +{\ex \lstinline| s[5]|} -- Elements can be accessed with their index + +Strings are immutable. diff -r 88a01948450d -r d33698326409 getting_started_with_strings/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_strings/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,191 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you should know -- + +.. 1. How to define strings +.. #. Different ways of defining a string +.. #. How to concatenate strings +.. #. How to print a string repeatedly +.. #. Accessing individual elements of the string +.. #. Immutability of strings + +.. Prerequisites +.. ------------- + +.. 1. getting started with ipython + +.. Author : Madhu + Internal Reviewer : Punch + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <15-11-2010, Anand, OK> [2010-10-05] + +Script +------ + +{{{ Show the slide containing the title }}} + +Hello friends. Welcome to this spoken tutorial on Getting started with +strings. + +{{{ Show the slide containing the outline }}} + +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 }}} + +To begin with let us start ipython, by typing:: + + ipython + +on the terminal + +So, what are strings? In Python anything within either single quotes +or double quotes or triple single quotes or triple double quotes are +strings. + +{{{ Type in ipython the following and read them as you type }}}:: + + 'This is a string' + "This is a string too' + '''This is a string as well''' + """This is also a string""" + 'p' + "" + +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" + +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-line strings without +using any escaping. Everything within the triple quotes is a single +string no matter how many lines it extends:: + + """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.""" + +We can assign this string to any variable:: + + a = 'Hello, World!' + +Now 'a' is a string variable. String is a collection of characters. In +addition string is an immutable collection. So all the operations that +are applicable to any other immutable collection in Python works on +string as well. So we can add two strings:: + + a = 'Hello' + b = 'World' + c = a + ', ' + b + '!' + +We can add string variables as well as the strings themselves all in +the same statement. The addition operation performs the concatenation +of two strings. + +Similarly we can multiply a string with an integer:: + + a = 'Hello' + a * 5 + +gives another string in which the original string 'Hello' is repeated +5 times. + +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 and goes up to n-1 for the last character. We +can access the strings from the end using negative indices:: + + a[-1] + +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' + a[0] = 'H' + +As said earlier, strings are immutable. We cannot manipulate a +string. Although there are some methods which let us manipulate +strings, we will look at them in the advanced session on strings. In +addition to the methods that let us manipulate the strings we have +methods like split which lets us break the string on the specified +separator, the join method which lets us combine the list of strings +into a single string based on the specified separator. + +{{{ Show summary slide }}} + +This brings us to the end of another session. In this tutorial session +we learnt + + * How to define strings + * Different ways of defining a string + * String concatenation and repetition + * Accessing individual elements of the string + * Immutability of strings + +{{{ 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 88a01948450d -r d33698326409 getting_started_with_strings/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_strings/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,80 @@ +#+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: +#+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 strings +*** Concatenation +*** Accessing individual elements +*** Immutability of strings +* Question 1 + Obtain the string ~%% -------------------- %%~ (20 hyphens) without + typing out all the twenty hyphens. +* Solution 1 + #+begin_src python + s = "%% " + "-"*20 + " %%" + #+end_src +* Question 2 + 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 + 'W' + 'e' + IndexError + #+end_src +* Summary + 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}{} + \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 88a01948450d -r d33698326409 getting_started_with_strings/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_strings/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,129 @@ +% Created 2010-11-10 Wed 10:46 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\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}} + +\title{} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + + + + + + + + + + + +\begin{frame} +\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{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} + + 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{Solution 2} +\label{sec-5} + +\lstset{language=Python} +\begin{lstlisting} +'W' +'e' +IndexError +\end{lstlisting} +\end{frame} +\begin{frame} +\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 + \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 88a01948450d -r d33698326409 getting_started_with_symbolics/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_symbolics/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,61 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. How do you define a name 'y' as a symbol? + + + Answer: var('y') + +2. List out some constants pre-defined in sage? + + Answer: pi, e ,euler_gamma + +3. List the functions for differentiation and integration in sage? + + Answer: diff and integral + +4. Get the value of pi upto precision 5 digits using sage? + + Answer: n(pi,5) + +5. Find third order differential of function. + + f(x)=sin(x^2)+exp(x^3) + + Answer: diff(f(x),x,3) + +6. What is the function to find factors of an expression? + + Answer: factor + +7. What is syntax for simplifying a function f? + + Answer f.simplify_full() + +8. Find the solution for x between pi/2 to pi for the given equation? + + sin(x)==cos(x^3)+exp(x^4) + find_root(sin(x)==cos(x^3)+exp(x^4),pi/2,pi) + +9. Create a simple two dimensional matrix with two symbolic variables? + + var('a,b') + A=matrix([[a,1],[2,b]]) + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1.Find the points of intersection of the circles + + x^2 + y^2 - 4x = 1 + x^2 + y^2 - 2y = 9 + +2. Integrate the function + +x^2*cos(x) + +between 1 to 3. diff -r 88a01948450d -r d33698326409 getting_started_with_symbolics/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_symbolics/quickref.tex Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 getting_started_with_symbolics/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_symbolics/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,340 @@ +.. Objectives +.. ---------- + +.. By the end of this tutorial, you will be able to + +.. 1. 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. + + +.. Prerequisites +.. ------------- + +.. 1. getting started with sage notebook + + +.. Author : Amit + Internal Reviewer : + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <, if OK> [2010-10-05] + +Symbolics with Sage +------------------- + +Hello friends and welcome to the tutorial on Symbolics with Sage. + +{{{ Show welcome slide }}} + +During the course of the tutorial we will learn + +{{{ Show outline slide }}} + +* 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. + +In addtion to a lot of other things, Sage can do Symbolic Math and we shall +start with defining symbolic expressions in Sage. + +Have your Sage notebook opened. If not, pause the video and +start you Sage notebook right now. + +On the sage notebook type:: + + sin(y) + +It raises a name error saying that ``y`` is not defined. We need to +declare ``y`` as a symbol. We do it using the ``var`` function. +:: + + var('y') + +Now if you type:: + + sin(y) + +Sage simply returns the expression. + +Sage treats ``sin(y)`` as a symbolic expression. We can use this to do +symbolic math using Sage's built-in constants and expressions. + +Let us try out a few examples. :: + + var('x,alpha,y,beta') + x^2/alpha^2+y^2/beta^2 + +We have defined 4 variables, ``x``, ``y``, ``alpha`` and ``beta`` and +have defined a symbolic expression using them. + +Here is an expression in ``theta`` :: + + var('theta') + sin(theta)*sin(theta)+cos(theta)*cos(theta) + +Now that you know how to define symbolic expressions in Sage, here is +an exercise. + +{{ show slide showing question 1 }} + +%% %% 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. + +The solution is on your screen. + +{{ show slide showing solution 1 }} + +Sage also provides built-in constants which are commonly used in +mathematics, for instance pi, e, infinity. The function ``n`` gives +the numerical values of all these constants. +:: + n(pi) + n(e) + n(oo) + +If you look into the documentation of function ``n`` by doing + +:: + n( + +You will see what all arguments it takes and what it returns. It will +be very helpful if you look at the documentation of all functions +introduced in the course of this script. + +Also we can define the number of digits we wish to have in the +constants. For this we have to pass an argument -- digits. Type + +:: + + n(pi, digits = 10) + +Apart from the constants Sage also has a lot of built-in functions +like ``sin``, ``cos``, ``log``, ``factorial``, ``gamma``, ``exp``, +``arcsin`` etc ... + +Lets try some of them out on the Sage notebook. +:: + + sin(pi/2) + + arctan(oo) + + log(e,e) + +Following are exercises that you must do. + +{{ show slide showing question 2 }} + +%% %% 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 + +{{ show slide showing solution 2 }} + +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('f',x) + +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. Let us define a function which is a parabola between 0 +to 1 and a constant from 1 to 2 . Type the following +:: + + + var('x') + h(x)=x^2 + g(x)=1 + + f=Piecewise([[(0,1),h(x)],[(1,2),g(x)]],x) + f + +We can also define functions convergent series and other series. + +We first define a function f(n) in the way discussed above.:: + + var('n') + function('f', n) + + +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) + + +Lets us now try another series :: + + + f(n) = (-1)^(n-1)*1/(2*n - 1) + sum(f(n), n, 1, oo) + +This series converges to pi/4. + +Following are exercises that you must do. + +{{ show slide showing question 3 }} + +%% %% 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. + +{{ show slide showing solution 3 }} + +Moving on let us see how to perform simple calculus operations using Sage + +For example lets try an expression first :: + + diff(x**2+sin(x),x) + +The diff function differentiates an expression or a function. It's +first argument is expression or function and second argument is the +independent variable. + +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 differential we need to add an extra third argument +for order :: + + diff(f(x),x,3) + +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 + +Many a times we need to find factors of an expression, we can use the +"factor" function + +:: + + y = (x^100 - x^70)*(cos(x)^2 + cos(x)^2*tan(x)^2) + f = factor(y) + +One can simplify complicated expression :: + + f.simplify_full() + +This simplifies the expression fully. We can also do simplification of +just the algebraic part and the trigonometric part :: + + f.simplify_exp() + f.simplify_trig() + +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) + +Let's 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) + +as we can see when we substitute the value the answer is almost = 0 showing +the solution we got was correct. + +Following are a few exercises 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. + + +Lets us now try some matrix algebra symbolically :: + + var('a,b,c,d') + A=matrix([[a,1,0],[0,b,0],[0,c,d]]) + A + +Now lets do some of the matrix operations on this matrix +:: + A.det() + A.inverse() + + +Following is an (are) exercise(s) that you must do. + +%% %% 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 }}} + +That brings us to the end of this tutorial. In this tutorial we learnt +how to + +* define symbolic expression and functions +* use built-in constants and functions +* use to see the documentation of a function +* do simple calculus +* substitute values in expressions using ``substitute`` function +* create symbolic matrices and perform operations on them + diff -r 88a01948450d -r d33698326409 getting_started_with_symbolics/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_symbolics/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,160 @@ +#+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. + +* Question 1 + - Define the following expression as symbolic + expression in sage. + + - x^2+y^2 + - y^2-4ax + +* Solution 1 +#+begin_src python + var('x,y') + x^2+y^2 + + var('a,x,y') + y^2-4*a*x +#+end_src python +* Question 2 + - Find the values of the following constants upto 6 digits precision + + - pi^2 + - euler_gamma^2 + + + - Find the value of the following. + + - sin(pi/4) + - ln(23) + +* Solution 2 +#+begin_src python + n(pi^2,digits=6) + n(sin(pi/4)) + n(log(23,e)) +#+end_src python +* Question 3 + - 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 3 +#+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 + +#+begin_src python + var('n') + f=1/(n^2-1) + sum(f(n), n, 1, oo) +#+end_src python + +* Question 4 + - Differentiate the following. + + - sin(x^3)+log(3x), to the second order + - x^5*log(x^7), to the fourth order + + - 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. + +* Solution 4 +#+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 5 + - Find the determinant and inverse of : + + A=[[x,0,1][y,1,0][z,0,y]] + +* Solution 5 +#+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. + - 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 88a01948450d -r d33698326409 getting_started_with_symbolics/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting_started_with_symbolics/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,252 @@ +% Created 2010-11-11 Thu 02:03 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\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}} + +\title{Getting started with symbolics} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\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{Question 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{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +var('x,y') +x^2+y^2 + +var('a,x,y') +y^2-4*a*x +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + +\begin{itemize} +\item Find the values of the following constants upto 6 digits precision + +\begin{itemize} +\item pi$^2$ +\item euler$_{\mathrm{gamma}}$$^2$ +\end{itemize} + +\end{itemize} + +\begin{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{Solution 2} +\label{sec-5} + +\lstset{language=Python} +\begin{lstlisting} +n(pi^2,digits=6) +n(sin(pi/4)) +n(log(23,e)) +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + +\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 3} +\label{sec-7} + +\lstset{language=Python} +\begin{lstlisting} +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{lstlisting} + +\lstset{language=Python} +\begin{lstlisting} +var('n') +f=1/(n^2-1) +sum(f(n), n, 1, oo) +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-8} + +\begin{itemize} +\item Differentiate the following. + +\begin{itemize} +\item sin(x$^3$)+log(3x), to the second order +\item x$^5$*log(x$^7$), to the fourth order +\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{Solution 4} +\label{sec-9} + +\lstset{language=Python} +\begin{lstlisting} +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{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 5} +\label{sec-10} + +\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 5} +\label{sec-11} + +\lstset{language=Python} +\begin{lstlisting} +var('x,y,z') +A=matrix([[x,0,1],[y,1,0],[z,0,y]]) +A.det() +A.inverse() +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-12} + +\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. +\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-13} + + \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 88a01948450d -r d33698326409 least_square_fit/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/least_square_fit/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,32 @@ +Objective Questions +------------------- + + 1. What does ones_like([1, 2, 3]) produce + + a. array([1, 1, 1]) + #. [1, 1, 1] + #. [1.0, 1.0, 1.0] + #. Error + + Answer: array([1, 1, 1]) + + 2. What does ones_like([1.2, 3, 4, 5]) produce + + a. [1.2, 3, 4, 5] + #. array([1.0, 1.0, 1.0, 1.0]) + #. array([1, 1, 1, 1]) + #. array([1.2, 3, 4, 5]) + + Answer: array([1.0, 1.0, 1.0, 1.0]) + + 3. The plot of ``u`` vs ``v`` is a bunch of scattered points that show a + linear trend. How do you find the least square fit line of ``u`` vs ``v``. + + Answer:: + + A = array(u, ones_like(u)).T + result = lstsq(A, v) + m, c = result[0] + + lst_line = m * u + c + diff -r 88a01948450d -r d33698326409 least_square_fit/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/least_square_fit/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,15 @@ +Creating a matrix with all ones:\\ +{\ex \lstinline| o = ones_like(l)|} + +Creating the A matrix:\\ +{\ex \lstinline| A = array(l, ones_like(l)).T|} + +Computing least square:\\ +{\ex \lstinline| result = lstsq(A, tsq)|} + +Obtaining the m and c values:\\ +{\ex \lstinline| m, c = result[0]|} + +Computing the least square fit line:\\ +{\ex \lstinline| lst_line = m * l + c|} + diff -r 88a01948450d -r d33698326409 least_square_fit/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/least_square_fit/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,148 @@ +.. Objectives +.. ---------- + +.. Plotting a least square fit line + +.. Prerequisites +.. ------------- + +.. 1. Basic Plotting +.. 2. Arrays +.. 3. Loading data from files + +.. Author : Nishanth Amuluru + Internal Reviewer : Punch + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : [2010-10-05] + + +.. #[Puneeth: Add pre-requisites.] + +Script +------ + +Hello friends and welcome to the tutorial on Least Square Fit + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall look at generating the least square fit line for a +given set of points. + +First let us have a look at the problem. + +{{{ Show the slide containing problem statement. }}} + +We have an input file generated from a simple pendulum experiment. + +It contains two columns of data. The first column is the length of the +pendulum and the second is the corresponding time period of the pendulum. + +As we know, the square of time period of a pendulum is directly proportional to +its length, we shall plot l vs t^2 and verify this. + +.. #[Puneeth:] removed the explanation about loadtxt and unpack +.. option. It's been done in another LO already. simple dependency +.. should work? + +To read the input file and parse the data, we are going to use the +loadtxt function. Type +:: + + l, t = loadtxt("/home/fossee/pendulum.txt", unpack=True) + l + t + +We can see that l and t are two sequences containing length and time values +correspondingly. + +Let us first plot l vs t^2. Type +:: + + tsq = t * t + plot(l, tsq, 'bo') + +{{{ switch to the plot window }}} + +.. #[Puneeth:] Moved explanation of least square fit here. seems more +.. apt. + +We can see that there is a visible linear trend, but we do not get a +straight line connecting them. We shall, therefore, generate a least +square fit line. + +{{{ show the slide containing explanation on least square fit }}} + +As shown in the slide, we are first going to generate the two matrices +tsq and A. Then we are going to use the ``lstsq`` function to find the +values of m and c. + +let us now generate the A matrix with l values. +We shall first generate a 2 x 90 matrix with the first row as l values and the +second row as ones. Then take the transpose of it. Type +:: + + inter_mat = array((l, ones_like(l))) + inter_mat + +We see that we have intermediate matrix. Now we need the transpose. Type +:: + + A = inter_mat.T + A + +Now we have both the matrices A and tsq. We only need to use the ``lstsq`` +Type +:: + + result = lstsq(A, tsq) + +The result is a sequence of values. The first item in this sequence, +is the matrix p i.e., the values of m and c. Hence, +:: + + m, c = result[0] + m + c + +Now that we have m and c, we need to generate the fitted values of t^2. Type +:: + + tsq_fit = m * l + c + plot(l, tsq, 'bo') + plot(l, tsq_fit, 'r') + +We get the least square fit of l vs t^2 + +{{{ Pause here and try out the following exercises }}} + +%% 2 %% change the label on y-axis to "y" and save the lines of code + accordingly + +{{{ continue from paused state }}} + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have learnt + + * how to generate a least square fit + +{{{ 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 + + +.. + Local Variables: + mode: rst + indent-tabs-mode: nil + sentence-end-double-space: nil + fill-column: 75 + End: diff -r 88a01948450d -r d33698326409 least_square_fit/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/least_square_fit/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,52 @@ +#+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: Least square fit +#+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 + - Plotting a Least square fit line +* Summary + You should now be able to -- + - Plot a least square fit line. +* 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 88a01948450d -r d33698326409 least_square_fit/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/least_square_fit/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,77 @@ +% Created 2010-10-10 Sun 19:02 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\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}} + +\title{Least square fit} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Plotting a Least square fit line +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-2} + + You should now be able to -- +\begin{itemize} +\item Plot a least square fit line. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-3} + + \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 88a01948450d -r d33698326409 loading-data-from-files/pendulum.txt --- a/loading-data-from-files/pendulum.txt Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,90 +0,0 @@ -1.0000e-01 6.9004e-01 -1.1000e-01 6.9497e-01 -1.2000e-01 7.4252e-01 -1.3000e-01 7.5360e-01 -1.4000e-01 8.3568e-01 -1.5000e-01 8.6789e-01 -1.6000e-01 8.4182e-01 -1.7000e-01 8.5379e-01 -1.8000e-01 8.5762e-01 -1.9000e-01 8.8390e-01 -2.0000e-01 8.9985e-01 -2.1000e-01 9.8436e-01 -2.2000e-01 1.0244e+00 -2.3000e-01 1.0572e+00 -2.4000e-01 9.9077e-01 -2.5000e-01 1.0058e+00 -2.6000e-01 1.0727e+00 -2.7000e-01 1.0943e+00 -2.8000e-01 1.1432e+00 -2.9000e-01 1.1045e+00 -3.0000e-01 1.1867e+00 -3.1000e-01 1.1385e+00 -3.2000e-01 1.2245e+00 -3.3000e-01 1.2406e+00 -3.4000e-01 1.2071e+00 -3.5000e-01 1.2658e+00 -3.6000e-01 1.2995e+00 -3.7000e-01 1.3142e+00 -3.8000e-01 1.2663e+00 -3.9000e-01 1.2578e+00 -4.0000e-01 1.2991e+00 -4.1000e-01 1.3058e+00 -4.2000e-01 1.3478e+00 -4.3000e-01 1.3506e+00 -4.4000e-01 1.4044e+00 -4.5000e-01 1.3948e+00 -4.6000e-01 1.3800e+00 -4.7000e-01 1.4480e+00 -4.8000e-01 1.4168e+00 -4.9000e-01 1.4719e+00 -5.0000e-01 1.4656e+00 -5.1000e-01 1.4399e+00 -5.2000e-01 1.5174e+00 -5.3000e-01 1.4988e+00 -5.4000e-01 1.4751e+00 -5.5000e-01 1.5326e+00 -5.6000e-01 1.5297e+00 -5.7000e-01 1.5372e+00 -5.8000e-01 1.6094e+00 -5.9000e-01 1.6352e+00 -6.0000e-01 1.5843e+00 -6.1000e-01 1.6643e+00 -6.2000e-01 1.5987e+00 -6.3000e-01 1.6585e+00 -6.4000e-01 1.6317e+00 -6.5000e-01 1.7074e+00 -6.6000e-01 1.6654e+00 -6.7000e-01 1.6551e+00 -6.8000e-01 1.6964e+00 -6.9000e-01 1.7143e+00 -7.0000e-01 1.7706e+00 -7.1000e-01 1.7622e+00 -7.2000e-01 1.7260e+00 -7.3000e-01 1.8089e+00 -7.4000e-01 1.7905e+00 -7.5000e-01 1.7428e+00 -7.6000e-01 1.8381e+00 -7.7000e-01 1.8182e+00 -7.8000e-01 1.7865e+00 -7.9000e-01 1.7995e+00 -8.0000e-01 1.8296e+00 -8.1000e-01 1.8625e+00 -8.2000e-01 1.8623e+00 -8.3000e-01 1.8383e+00 -8.4000e-01 1.8593e+00 -8.5000e-01 1.8944e+00 -8.6000e-01 1.9598e+00 -8.7000e-01 1.9000e+00 -8.8000e-01 1.9244e+00 -8.9000e-01 1.9397e+00 -9.0000e-01 1.9440e+00 -9.1000e-01 1.9718e+00 -9.2000e-01 1.9383e+00 -9.3000e-01 1.9555e+00 -9.4000e-01 2.0006e+00 -9.5000e-01 1.9841e+00 -9.6000e-01 2.0066e+00 -9.7000e-01 2.0493e+00 -9.8000e-01 2.0503e+00 -9.9000e-01 2.0214e+00 diff -r 88a01948450d -r d33698326409 loading-data-from-files/pendulum_semicolon.txt --- a/loading-data-from-files/pendulum_semicolon.txt Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,90 +0,0 @@ -1.0000e-01;6.9004e-01 -1.1000e-01;6.9497e-01 -1.2000e-01;7.4252e-01 -1.3000e-01;7.5360e-01 -1.4000e-01;8.3568e-01 -1.5000e-01;8.6789e-01 -1.6000e-01;8.4182e-01 -1.7000e-01;8.5379e-01 -1.8000e-01;8.5762e-01 -1.9000e-01;8.8390e-01 -2.0000e-01;8.9985e-01 -2.1000e-01;9.8436e-01 -2.2000e-01;1.0244e+00 -2.3000e-01;1.0572e+00 -2.4000e-01;9.9077e-01 -2.5000e-01;1.0058e+00 -2.6000e-01;1.0727e+00 -2.7000e-01;1.0943e+00 -2.8000e-01;1.1432e+00 -2.9000e-01;1.1045e+00 -3.0000e-01;1.1867e+00 -3.1000e-01;1.1385e+00 -3.2000e-01;1.2245e+00 -3.3000e-01;1.2406e+00 -3.4000e-01;1.2071e+00 -3.5000e-01;1.2658e+00 -3.6000e-01;1.2995e+00 -3.7000e-01;1.3142e+00 -3.8000e-01;1.2663e+00 -3.9000e-01;1.2578e+00 -4.0000e-01;1.2991e+00 -4.1000e-01;1.3058e+00 -4.2000e-01;1.3478e+00 -4.3000e-01;1.3506e+00 -4.4000e-01;1.4044e+00 -4.5000e-01;1.3948e+00 -4.6000e-01;1.3800e+00 -4.7000e-01;1.4480e+00 -4.8000e-01;1.4168e+00 -4.9000e-01;1.4719e+00 -5.0000e-01;1.4656e+00 -5.1000e-01;1.4399e+00 -5.2000e-01;1.5174e+00 -5.3000e-01;1.4988e+00 -5.4000e-01;1.4751e+00 -5.5000e-01;1.5326e+00 -5.6000e-01;1.5297e+00 -5.7000e-01;1.5372e+00 -5.8000e-01;1.6094e+00 -5.9000e-01;1.6352e+00 -6.0000e-01;1.5843e+00 -6.1000e-01;1.6643e+00 -6.2000e-01;1.5987e+00 -6.3000e-01;1.6585e+00 -6.4000e-01;1.6317e+00 -6.5000e-01;1.7074e+00 -6.6000e-01;1.6654e+00 -6.7000e-01;1.6551e+00 -6.8000e-01;1.6964e+00 -6.9000e-01;1.7143e+00 -7.0000e-01;1.7706e+00 -7.1000e-01;1.7622e+00 -7.2000e-01;1.7260e+00 -7.3000e-01;1.8089e+00 -7.4000e-01;1.7905e+00 -7.5000e-01;1.7428e+00 -7.6000e-01;1.8381e+00 -7.7000e-01;1.8182e+00 -7.8000e-01;1.7865e+00 -7.9000e-01;1.7995e+00 -8.0000e-01;1.8296e+00 -8.1000e-01;1.8625e+00 -8.2000e-01;1.8623e+00 -8.3000e-01;1.8383e+00 -8.4000e-01;1.8593e+00 -8.5000e-01;1.8944e+00 -8.6000e-01;1.9598e+00 -8.7000e-01;1.9000e+00 -8.8000e-01;1.9244e+00 -8.9000e-01;1.9397e+00 -9.0000e-01;1.9440e+00 -9.1000e-01;1.9718e+00 -9.2000e-01;1.9383e+00 -9.3000e-01;1.9555e+00 -9.4000e-01;2.0006e+00 -9.5000e-01;1.9841e+00 -9.6000e-01;2.0066e+00 -9.7000e-01;2.0493e+00 -9.8000e-01;2.0503e+00 -9.9000e-01;2.0214e+00 diff -r 88a01948450d -r d33698326409 loading-data-from-files/primes.txt --- a/loading-data-from-files/primes.txt Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,25 +0,0 @@ -2 -3 -5 -7 -11 -13 -17 -19 -23 -29 -31 -37 -41 -43 -47 -53 -59 -61 -67 -71 -73 -79 -83 -89 -97 diff -r 88a01948450d -r d33698326409 loading-data-from-files/questions.rst --- a/loading-data-from-files/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,67 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here. - -1. ``loadtxt`` can read data only from a file with one column - only. True or False? - - Answer: False - -#. To read a file with multiple columns, into separate simple - sequences, ``loadtxt`` is given the additional argument ______? - - Answer: ``unpack=True`` - -#. We have a file with two columns of data separated by one of the - following characters. Which of them doesn't require the delimiter - argument to be specified, when using ``loadtxt``. - - a. ; - #. , - #. : - #. [space] - - Answer: [space] - -#. Given a file ``data.txt`` with three columns of data separated by - spaces, read it into one complex sequence. - - Answer: ``x = loadtxt("data.txt")`` - -#. Given a file ``data.txt`` with three columns of data separated by - spaces, read it into 3 separate simple sequences. - - Answer: ``x = loadtxt("data.txt", unpack=True)`` - -#. Given a file ``data.txt`` with three columns of data separated by - ``:``, read it into one complex sequence. - - Answer: ``x = loadtxt("data.txt", delimiter=":")`` - -#. Given a file ``data.txt`` with three columns of data separated by - ":", read it into 3 separate simple sequences. - - Answer: ``x = loadtxt("data.txt", unpack=True, delimiter=":")`` - -#. To use the loadtxt command, each row should have the same number of - values, T or F ? - - Answer: True - -Larger Questions ----------------- - -.. A minimum of 2 questions here. - -1. What will happen if one of the cells is empty? - -#. Given a file with 3 columns of data but two different delimiters, - what do you think will happen? - -#. Read a column with text? - -#. An input file contains 5 columns of data. Use only the second and fourth - columns of data and load into two different variables. - [hint: read the documentation, use the argument ``usecols``] -.. #[bhanu: solutions are not seen to have been included.] diff -r 88a01948450d -r d33698326409 loading-data-from-files/quickref.tex --- a/loading-data-from-files/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,12 +0,0 @@ -\textbf{Loading data from files} - -\lstinline|loadtxt('filename')| returns the columns of file in one -sequence. - -\lstinline|x, y = loadtxt('filename', unpack=True)| to obtain a file -with 2 columns in separate sequences. - -\lstinline|loadtxt('filename', delimiter=';')|, if the file has -columns separated by ';' instead of spaces/tabs. - - diff -r 88a01948450d -r d33698326409 loading-data-from-files/script.rst --- a/loading-data-from-files/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,180 +0,0 @@ -.. Objectives -.. ---------- - -.. At the end of this tutorial, you will be able to - -.. + Read data from files, containing a single column of data using the -.. ``loadtxt`` command. -.. + Read multiple columns of data, separated by spaces or other -.. delimiters. - - -.. Prerequisites -.. ------------- - -.. 1. getting started with ``ipython`` - -.. #[Anand: author and internal reviewer not mentioned] -.. Author : Puneeth Changanti - Internal Reviewer : Nishanth Amuluru - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <06-11-2010 Anand, OK> [2010-10-05] - -Script ------- - -{{{ Show the slide containing title }}} - -Hello Friends. Welcome to this tutorial on loading data from files. - -{{{ Screen shows welcome slide }}} - -We often require to plot points obtained from experimental -observations. In this tutorial we shall learn to read data from files -and save it into sequences that can later be used to plot. - -{{{ Show the outline for this tutorial }}} - -We shall use the ``loadtxt`` command to load data from files. We will -be looking at how to read a file with multiple columns of data and -load each column of data into a sequence. - -{{{ switch back to the terminal }}} - -As usual, let us start IPython, using -:: - - ipython -pylab - -Now, Let us begin with reading the file primes.txt, which contains -just a list of primes listed in a column, using the loadtxt command. -The file, in our case, is present in ``/home/fossee/primes.txt``. - -{{{ Navigate to the path in the OS, open the file and show it }}} - -.. #[punch: do we need a slide for showing the path?] - -.. We use the ``cat`` command to see the contents of this file. - -.. #[punch: should we show the cat command here? seems like a good place - to do it] :: - - cat /home/fossee/primes.txt - -.. #[Nishanth]: A problem for windows users. - Should we simply open the file and show them the data - so that we can be fine with GNU/Linux ;) and windows? - -Now let us read this list into the variable ``primes``. -:: - - primes = loadtxt('/home/fossee/primes.txt') - -``primes`` is now a sequence of primes, that was listed in the file, -``primes.txt``. - -We now type, ``print primes`` to see the sequence printed. - -We observe that all of the numbers end with a period. This is so, -because these numbers are actually read as ``floats``. We shall learn -about them, later. - -Now, let us use the ``loadtxt`` command to read a file that contains -two columns of data, ``pendulum.txt``. This file contains the length -of the pendulum in the first column and the corresponding time period -in the second. Note that ``loadtxt`` needs both the columns to have -equal number of rows. - -.. Following is an exercise that you must do. - -.. %%1%% Use the ``cat`` command to view the contents of this file. - -.. Please, pause the video here. Do the exercise and then continue. - -.. This is how we look at the contents of the file, ``pendulum.txt`` -.. :: - -.. cat /home/fossee/pendulum.txt - -.. #[Nishanth]: The first column is L values and second is T values - from a simple pendulum experiment. - Since you are using the variable names later in the - script. - Not necessary but can be included also. - -Let us, now, read the data into the variable ``pend``. Again, it is -assumed that the file is in ``/home/fossee/`` -:: - - pend = loadtxt('/home/fossee/pendulum.txt') - -Let us now print the variable ``pend`` and see what's in it. -:: - - print pend - -Notice that ``pend`` is not a simple sequence like ``primes``. It has -two sequences, containing both the columns of the data file. Let us -use an additional argument of the ``loadtxt`` command, to read it into -two separate, simple sequences. -:: - - L, T = loadtxt('/home/fossee/pendulum.txt', unpack=True) - -.. #[Nishanth]: It has a sequence of items in which each item contains - two values. first is l and second is t - -Let us now, print the variables L and T, to see what they contain. -:: - - print L - print T - -.. #[Nishanth]: Stress on ``unpack=True`` ?? - -Notice, that L and T now contain the first and second columns of data -from the data file, ``pendulum.txt``, and they are both simple -sequences. ``unpack=True`` has given us the two columns into two -separate sequences instead of one complex sequence. - -{{{ show the slide with loadtxt --- other features }}} - -In this tutorial, we have learnt the basic use of the ``loadtxt`` -command, which is capable of doing a lot more than we have used it for -until now. Let us look at an example, but before that do this -exercise. - -%%1%% Read the file ``pendulum_semicolon.txt`` which contains the same -data as ``pendulum.txt``, but the columns are separated by semi-colons -instead of spaces. Use the IPython help to see how to do this. - -Please, pause the video here. Do the exercise and then continue. - -{{{ switch back to the terminal }}} -:: - - L, T = loadtxt('/home/fossee/pendulum_semicolon.txt', unpack=True, delimiter=';') - - print L - - print T - -This brings us to the end of this tutorial. - -{{{ show the summary slide }}} - -You should now be able to do the following, comfortably. - - + Read data from files, containing a single column of data using the - ``loadtxt`` command. - + Read multiple columns of data, separated by spaces or other - delimiters. - -{{{ 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 88a01948450d -r d33698326409 loading-data-from-files/slides.org --- a/loading-data-from-files/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,67 +0,0 @@ -#+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: Loading data from files -#+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 - + Read data from files with a single column of data - + Read data from files with multiple columns -* Question 1 - Read the file ~pendulum_semicolon.txt~ which contains the same data - as ~pendulum.txt~, but the columns are separated by semi-colons - instead of spaces. Use the IPython help to see how to do this. -* Solution 1 - #+begin_src python - In []: L, T = loadtxt('/home/fossee/pendulum_semicolon.txt', unpack=True, delimiter=';') - - In []: print L - - In []: print T - #+end_src -* Summary - + Read data from files, containing a single column of data using the - ~loadtxt~ command. - + Read multiple columns of data, separated by spaces or other - delimiters. -* 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 88a01948450d -r d33698326409 loading-data-from-files/slides.tex --- a/loading-data-from-files/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,101 +0,0 @@ -% Created 2010-10-10 Sun 18:12 -\documentclass[presentation]{beamer} -\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\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}} - -\title{Loading data from files} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Read data from files with a single column of data -\item Read data from files with multiple columns -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Question 1} -\label{sec-2} - - Read the file \texttt{pendulum\_semicolon.txt} which contains the same data - as \texttt{pendulum.txt}, but the columns are separated by semi-colons - instead of spaces. Use the IPython help to see how to do this. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 1} -\label{sec-3} - -\lstset{language=Python} -\begin{lstlisting} -In []: L, T = loadtxt('/home/fossee/pendulum_semicolon.txt', unpack=True, delimiter=';') - -In []: print L - -In []: print T -\end{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-4} - -\begin{itemize} -\item Read data from files, containing a single column of data using the - \texttt{loadtxt} command. -\item Read multiple columns of data, separated by spaces or other - delimiters. -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-5} - - \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 88a01948450d -r d33698326409 loading_data_from_files/pendulum.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading_data_from_files/pendulum.txt Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,90 @@ +1.0000e-01 6.9004e-01 +1.1000e-01 6.9497e-01 +1.2000e-01 7.4252e-01 +1.3000e-01 7.5360e-01 +1.4000e-01 8.3568e-01 +1.5000e-01 8.6789e-01 +1.6000e-01 8.4182e-01 +1.7000e-01 8.5379e-01 +1.8000e-01 8.5762e-01 +1.9000e-01 8.8390e-01 +2.0000e-01 8.9985e-01 +2.1000e-01 9.8436e-01 +2.2000e-01 1.0244e+00 +2.3000e-01 1.0572e+00 +2.4000e-01 9.9077e-01 +2.5000e-01 1.0058e+00 +2.6000e-01 1.0727e+00 +2.7000e-01 1.0943e+00 +2.8000e-01 1.1432e+00 +2.9000e-01 1.1045e+00 +3.0000e-01 1.1867e+00 +3.1000e-01 1.1385e+00 +3.2000e-01 1.2245e+00 +3.3000e-01 1.2406e+00 +3.4000e-01 1.2071e+00 +3.5000e-01 1.2658e+00 +3.6000e-01 1.2995e+00 +3.7000e-01 1.3142e+00 +3.8000e-01 1.2663e+00 +3.9000e-01 1.2578e+00 +4.0000e-01 1.2991e+00 +4.1000e-01 1.3058e+00 +4.2000e-01 1.3478e+00 +4.3000e-01 1.3506e+00 +4.4000e-01 1.4044e+00 +4.5000e-01 1.3948e+00 +4.6000e-01 1.3800e+00 +4.7000e-01 1.4480e+00 +4.8000e-01 1.4168e+00 +4.9000e-01 1.4719e+00 +5.0000e-01 1.4656e+00 +5.1000e-01 1.4399e+00 +5.2000e-01 1.5174e+00 +5.3000e-01 1.4988e+00 +5.4000e-01 1.4751e+00 +5.5000e-01 1.5326e+00 +5.6000e-01 1.5297e+00 +5.7000e-01 1.5372e+00 +5.8000e-01 1.6094e+00 +5.9000e-01 1.6352e+00 +6.0000e-01 1.5843e+00 +6.1000e-01 1.6643e+00 +6.2000e-01 1.5987e+00 +6.3000e-01 1.6585e+00 +6.4000e-01 1.6317e+00 +6.5000e-01 1.7074e+00 +6.6000e-01 1.6654e+00 +6.7000e-01 1.6551e+00 +6.8000e-01 1.6964e+00 +6.9000e-01 1.7143e+00 +7.0000e-01 1.7706e+00 +7.1000e-01 1.7622e+00 +7.2000e-01 1.7260e+00 +7.3000e-01 1.8089e+00 +7.4000e-01 1.7905e+00 +7.5000e-01 1.7428e+00 +7.6000e-01 1.8381e+00 +7.7000e-01 1.8182e+00 +7.8000e-01 1.7865e+00 +7.9000e-01 1.7995e+00 +8.0000e-01 1.8296e+00 +8.1000e-01 1.8625e+00 +8.2000e-01 1.8623e+00 +8.3000e-01 1.8383e+00 +8.4000e-01 1.8593e+00 +8.5000e-01 1.8944e+00 +8.6000e-01 1.9598e+00 +8.7000e-01 1.9000e+00 +8.8000e-01 1.9244e+00 +8.9000e-01 1.9397e+00 +9.0000e-01 1.9440e+00 +9.1000e-01 1.9718e+00 +9.2000e-01 1.9383e+00 +9.3000e-01 1.9555e+00 +9.4000e-01 2.0006e+00 +9.5000e-01 1.9841e+00 +9.6000e-01 2.0066e+00 +9.7000e-01 2.0493e+00 +9.8000e-01 2.0503e+00 +9.9000e-01 2.0214e+00 diff -r 88a01948450d -r d33698326409 loading_data_from_files/pendulum_semicolon.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading_data_from_files/pendulum_semicolon.txt Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,90 @@ +1.0000e-01;6.9004e-01 +1.1000e-01;6.9497e-01 +1.2000e-01;7.4252e-01 +1.3000e-01;7.5360e-01 +1.4000e-01;8.3568e-01 +1.5000e-01;8.6789e-01 +1.6000e-01;8.4182e-01 +1.7000e-01;8.5379e-01 +1.8000e-01;8.5762e-01 +1.9000e-01;8.8390e-01 +2.0000e-01;8.9985e-01 +2.1000e-01;9.8436e-01 +2.2000e-01;1.0244e+00 +2.3000e-01;1.0572e+00 +2.4000e-01;9.9077e-01 +2.5000e-01;1.0058e+00 +2.6000e-01;1.0727e+00 +2.7000e-01;1.0943e+00 +2.8000e-01;1.1432e+00 +2.9000e-01;1.1045e+00 +3.0000e-01;1.1867e+00 +3.1000e-01;1.1385e+00 +3.2000e-01;1.2245e+00 +3.3000e-01;1.2406e+00 +3.4000e-01;1.2071e+00 +3.5000e-01;1.2658e+00 +3.6000e-01;1.2995e+00 +3.7000e-01;1.3142e+00 +3.8000e-01;1.2663e+00 +3.9000e-01;1.2578e+00 +4.0000e-01;1.2991e+00 +4.1000e-01;1.3058e+00 +4.2000e-01;1.3478e+00 +4.3000e-01;1.3506e+00 +4.4000e-01;1.4044e+00 +4.5000e-01;1.3948e+00 +4.6000e-01;1.3800e+00 +4.7000e-01;1.4480e+00 +4.8000e-01;1.4168e+00 +4.9000e-01;1.4719e+00 +5.0000e-01;1.4656e+00 +5.1000e-01;1.4399e+00 +5.2000e-01;1.5174e+00 +5.3000e-01;1.4988e+00 +5.4000e-01;1.4751e+00 +5.5000e-01;1.5326e+00 +5.6000e-01;1.5297e+00 +5.7000e-01;1.5372e+00 +5.8000e-01;1.6094e+00 +5.9000e-01;1.6352e+00 +6.0000e-01;1.5843e+00 +6.1000e-01;1.6643e+00 +6.2000e-01;1.5987e+00 +6.3000e-01;1.6585e+00 +6.4000e-01;1.6317e+00 +6.5000e-01;1.7074e+00 +6.6000e-01;1.6654e+00 +6.7000e-01;1.6551e+00 +6.8000e-01;1.6964e+00 +6.9000e-01;1.7143e+00 +7.0000e-01;1.7706e+00 +7.1000e-01;1.7622e+00 +7.2000e-01;1.7260e+00 +7.3000e-01;1.8089e+00 +7.4000e-01;1.7905e+00 +7.5000e-01;1.7428e+00 +7.6000e-01;1.8381e+00 +7.7000e-01;1.8182e+00 +7.8000e-01;1.7865e+00 +7.9000e-01;1.7995e+00 +8.0000e-01;1.8296e+00 +8.1000e-01;1.8625e+00 +8.2000e-01;1.8623e+00 +8.3000e-01;1.8383e+00 +8.4000e-01;1.8593e+00 +8.5000e-01;1.8944e+00 +8.6000e-01;1.9598e+00 +8.7000e-01;1.9000e+00 +8.8000e-01;1.9244e+00 +8.9000e-01;1.9397e+00 +9.0000e-01;1.9440e+00 +9.1000e-01;1.9718e+00 +9.2000e-01;1.9383e+00 +9.3000e-01;1.9555e+00 +9.4000e-01;2.0006e+00 +9.5000e-01;1.9841e+00 +9.6000e-01;2.0066e+00 +9.7000e-01;2.0493e+00 +9.8000e-01;2.0503e+00 +9.9000e-01;2.0214e+00 diff -r 88a01948450d -r d33698326409 loading_data_from_files/primes.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading_data_from_files/primes.txt Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,25 @@ +2 +3 +5 +7 +11 +13 +17 +19 +23 +29 +31 +37 +41 +43 +47 +53 +59 +61 +67 +71 +73 +79 +83 +89 +97 diff -r 88a01948450d -r d33698326409 loading_data_from_files/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading_data_from_files/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,67 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here. + +1. ``loadtxt`` can read data only from a file with one column + only. True or False? + + Answer: False + +#. To read a file with multiple columns, into separate simple + sequences, ``loadtxt`` is given the additional argument ______? + + Answer: ``unpack=True`` + +#. We have a file with two columns of data separated by one of the + following characters. Which of them doesn't require the delimiter + argument to be specified, when using ``loadtxt``. + + a. ; + #. , + #. : + #. [space] + + Answer: [space] + +#. Given a file ``data.txt`` with three columns of data separated by + spaces, read it into one complex sequence. + + Answer: ``x = loadtxt("data.txt")`` + +#. Given a file ``data.txt`` with three columns of data separated by + spaces, read it into 3 separate simple sequences. + + Answer: ``x = loadtxt("data.txt", unpack=True)`` + +#. Given a file ``data.txt`` with three columns of data separated by + ``:``, read it into one complex sequence. + + Answer: ``x = loadtxt("data.txt", delimiter=":")`` + +#. Given a file ``data.txt`` with three columns of data separated by + ":", read it into 3 separate simple sequences. + + Answer: ``x = loadtxt("data.txt", unpack=True, delimiter=":")`` + +#. To use the loadtxt command, each row should have the same number of + values, T or F ? + + Answer: True + +Larger Questions +---------------- + +.. A minimum of 2 questions here. + +1. What will happen if one of the cells is empty? + +#. Given a file with 3 columns of data but two different delimiters, + what do you think will happen? + +#. Read a column with text? + +#. An input file contains 5 columns of data. Use only the second and fourth + columns of data and load into two different variables. + [hint: read the documentation, use the argument ``usecols``] +.. #[bhanu: solutions are not seen to have been included.] diff -r 88a01948450d -r d33698326409 loading_data_from_files/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading_data_from_files/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,12 @@ +\textbf{Loading data from files} + +\lstinline|loadtxt('filename')| returns the columns of file in one +sequence. + +\lstinline|x, y = loadtxt('filename', unpack=True)| to obtain a file +with 2 columns in separate sequences. + +\lstinline|loadtxt('filename', delimiter=';')|, if the file has +columns separated by ';' instead of spaces/tabs. + + diff -r 88a01948450d -r d33698326409 loading_data_from_files/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading_data_from_files/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,180 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. + Read data from files, containing a single column of data using the +.. ``loadtxt`` command. +.. + Read multiple columns of data, separated by spaces or other +.. delimiters. + + +.. Prerequisites +.. ------------- + +.. 1. getting started with ``ipython`` + +.. #[Anand: author and internal reviewer not mentioned] +.. Author : Puneeth Changanti + Internal Reviewer : Nishanth Amuluru + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <06-11-2010 Anand, OK> [2010-10-05] + +Script +------ + +{{{ Show the slide containing title }}} + +Hello Friends. Welcome to this tutorial on loading data from files. + +{{{ Screen shows welcome slide }}} + +We often require to plot points obtained from experimental +observations. In this tutorial we shall learn to read data from files +and save it into sequences that can later be used to plot. + +{{{ Show the outline for this tutorial }}} + +We shall use the ``loadtxt`` command to load data from files. We will +be looking at how to read a file with multiple columns of data and +load each column of data into a sequence. + +{{{ switch back to the terminal }}} + +As usual, let us start IPython, using +:: + + ipython -pylab + +Now, Let us begin with reading the file primes.txt, which contains +just a list of primes listed in a column, using the loadtxt command. +The file, in our case, is present in ``/home/fossee/primes.txt``. + +{{{ Navigate to the path in the OS, open the file and show it }}} + +.. #[punch: do we need a slide for showing the path?] + +.. We use the ``cat`` command to see the contents of this file. + +.. #[punch: should we show the cat command here? seems like a good place + to do it] :: + + cat /home/fossee/primes.txt + +.. #[Nishanth]: A problem for windows users. + Should we simply open the file and show them the data + so that we can be fine with GNU/Linux ;) and windows? + +Now let us read this list into the variable ``primes``. +:: + + primes = loadtxt('/home/fossee/primes.txt') + +``primes`` is now a sequence of primes, that was listed in the file, +``primes.txt``. + +We now type, ``print primes`` to see the sequence printed. + +We observe that all of the numbers end with a period. This is so, +because these numbers are actually read as ``floats``. We shall learn +about them, later. + +Now, let us use the ``loadtxt`` command to read a file that contains +two columns of data, ``pendulum.txt``. This file contains the length +of the pendulum in the first column and the corresponding time period +in the second. Note that ``loadtxt`` needs both the columns to have +equal number of rows. + +.. Following is an exercise that you must do. + +.. %%1%% Use the ``cat`` command to view the contents of this file. + +.. Please, pause the video here. Do the exercise and then continue. + +.. This is how we look at the contents of the file, ``pendulum.txt`` +.. :: + +.. cat /home/fossee/pendulum.txt + +.. #[Nishanth]: The first column is L values and second is T values + from a simple pendulum experiment. + Since you are using the variable names later in the + script. + Not necessary but can be included also. + +Let us, now, read the data into the variable ``pend``. Again, it is +assumed that the file is in ``/home/fossee/`` +:: + + pend = loadtxt('/home/fossee/pendulum.txt') + +Let us now print the variable ``pend`` and see what's in it. +:: + + print pend + +Notice that ``pend`` is not a simple sequence like ``primes``. It has +two sequences, containing both the columns of the data file. Let us +use an additional argument of the ``loadtxt`` command, to read it into +two separate, simple sequences. +:: + + L, T = loadtxt('/home/fossee/pendulum.txt', unpack=True) + +.. #[Nishanth]: It has a sequence of items in which each item contains + two values. first is l and second is t + +Let us now, print the variables L and T, to see what they contain. +:: + + print L + print T + +.. #[Nishanth]: Stress on ``unpack=True`` ?? + +Notice, that L and T now contain the first and second columns of data +from the data file, ``pendulum.txt``, and they are both simple +sequences. ``unpack=True`` has given us the two columns into two +separate sequences instead of one complex sequence. + +{{{ show the slide with loadtxt --- other features }}} + +In this tutorial, we have learnt the basic use of the ``loadtxt`` +command, which is capable of doing a lot more than we have used it for +until now. Let us look at an example, but before that do this +exercise. + +%%1%% Read the file ``pendulum_semicolon.txt`` which contains the same +data as ``pendulum.txt``, but the columns are separated by semi-colons +instead of spaces. Use the IPython help to see how to do this. + +Please, pause the video here. Do the exercise and then continue. + +{{{ switch back to the terminal }}} +:: + + L, T = loadtxt('/home/fossee/pendulum_semicolon.txt', unpack=True, delimiter=';') + + print L + + print T + +This brings us to the end of this tutorial. + +{{{ show the summary slide }}} + +You should now be able to do the following, comfortably. + + + Read data from files, containing a single column of data using the + ``loadtxt`` command. + + Read multiple columns of data, separated by spaces or other + delimiters. + +{{{ 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 88a01948450d -r d33698326409 loading_data_from_files/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading_data_from_files/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,67 @@ +#+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: Loading data from files +#+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 + + Read data from files with a single column of data + + Read data from files with multiple columns +* Question 1 + Read the file ~pendulum_semicolon.txt~ which contains the same data + as ~pendulum.txt~, but the columns are separated by semi-colons + instead of spaces. Use the IPython help to see how to do this. +* Solution 1 + #+begin_src python + In []: L, T = loadtxt('/home/fossee/pendulum_semicolon.txt', unpack=True, delimiter=';') + + In []: print L + + In []: print T + #+end_src +* Summary + + Read data from files, containing a single column of data using the + ~loadtxt~ command. + + Read multiple columns of data, separated by spaces or other + delimiters. +* 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 88a01948450d -r d33698326409 loading_data_from_files/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading_data_from_files/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,101 @@ +% Created 2010-10-10 Sun 18:12 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\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}} + +\title{Loading data from files} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Read data from files with a single column of data +\item Read data from files with multiple columns +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Read the file \texttt{pendulum\_semicolon.txt} which contains the same data + as \texttt{pendulum.txt}, but the columns are separated by semi-colons + instead of spaces. Use the IPython help to see how to do this. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +In []: L, T = loadtxt('/home/fossee/pendulum_semicolon.txt', unpack=True, delimiter=';') + +In []: print L + +In []: print T +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-4} + +\begin{itemize} +\item Read data from files, containing a single column of data using the + \texttt{loadtxt} command. +\item Read multiple columns of data, separated by spaces or other + delimiters. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-5} + + \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 88a01948450d -r d33698326409 lstsq/questions.rst --- a/lstsq/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,32 +0,0 @@ -Objective Questions -------------------- - - 1. What does ones_like([1, 2, 3]) produce - - a. array([1, 1, 1]) - #. [1, 1, 1] - #. [1.0, 1.0, 1.0] - #. Error - - Answer: array([1, 1, 1]) - - 2. What does ones_like([1.2, 3, 4, 5]) produce - - a. [1.2, 3, 4, 5] - #. array([1.0, 1.0, 1.0, 1.0]) - #. array([1, 1, 1, 1]) - #. array([1.2, 3, 4, 5]) - - Answer: array([1.0, 1.0, 1.0, 1.0]) - - 3. The plot of ``u`` vs ``v`` is a bunch of scattered points that show a - linear trend. How do you find the least square fit line of ``u`` vs ``v``. - - Answer:: - - A = array(u, ones_like(u)).T - result = lstsq(A, v) - m, c = result[0] - - lst_line = m * u + c - diff -r 88a01948450d -r d33698326409 lstsq/quickref.tex --- a/lstsq/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,15 +0,0 @@ -Creating a matrix with all ones:\\ -{\ex \lstinline| o = ones_like(l)|} - -Creating the A matrix:\\ -{\ex \lstinline| A = array(l, ones_like(l)).T|} - -Computing least square:\\ -{\ex \lstinline| result = lstsq(A, tsq)|} - -Obtaining the m and c values:\\ -{\ex \lstinline| m, c = result[0]|} - -Computing the least square fit line:\\ -{\ex \lstinline| lst_line = m * l + c|} - diff -r 88a01948450d -r d33698326409 lstsq/script.rst --- a/lstsq/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,148 +0,0 @@ -.. Objectives -.. ---------- - -.. Plotting a least square fit line - -.. Prerequisites -.. ------------- - -.. 1. Basic Plotting -.. 2. Arrays -.. 3. Loading data from files - -.. Author : Nishanth Amuluru - Internal Reviewer : Punch - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : [2010-10-05] - - -.. #[Puneeth: Add pre-requisites.] - -Script ------- - -Hello friends and welcome to the tutorial on Least Square Fit - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall look at generating the least square fit line for a -given set of points. - -First let us have a look at the problem. - -{{{ Show the slide containing problem statement. }}} - -We have an input file generated from a simple pendulum experiment. - -It contains two columns of data. The first column is the length of the -pendulum and the second is the corresponding time period of the pendulum. - -As we know, the square of time period of a pendulum is directly proportional to -its length, we shall plot l vs t^2 and verify this. - -.. #[Puneeth:] removed the explanation about loadtxt and unpack -.. option. It's been done in another LO already. simple dependency -.. should work? - -To read the input file and parse the data, we are going to use the -loadtxt function. Type -:: - - l, t = loadtxt("/home/fossee/pendulum.txt", unpack=True) - l - t - -We can see that l and t are two sequences containing length and time values -correspondingly. - -Let us first plot l vs t^2. Type -:: - - tsq = t * t - plot(l, tsq, 'bo') - -{{{ switch to the plot window }}} - -.. #[Puneeth:] Moved explanation of least square fit here. seems more -.. apt. - -We can see that there is a visible linear trend, but we do not get a -straight line connecting them. We shall, therefore, generate a least -square fit line. - -{{{ show the slide containing explanation on least square fit }}} - -As shown in the slide, we are first going to generate the two matrices -tsq and A. Then we are going to use the ``lstsq`` function to find the -values of m and c. - -let us now generate the A matrix with l values. -We shall first generate a 2 x 90 matrix with the first row as l values and the -second row as ones. Then take the transpose of it. Type -:: - - inter_mat = array((l, ones_like(l))) - inter_mat - -We see that we have intermediate matrix. Now we need the transpose. Type -:: - - A = inter_mat.T - A - -Now we have both the matrices A and tsq. We only need to use the ``lstsq`` -Type -:: - - result = lstsq(A, tsq) - -The result is a sequence of values. The first item in this sequence, -is the matrix p i.e., the values of m and c. Hence, -:: - - m, c = result[0] - m - c - -Now that we have m and c, we need to generate the fitted values of t^2. Type -:: - - tsq_fit = m * l + c - plot(l, tsq, 'bo') - plot(l, tsq_fit, 'r') - -We get the least square fit of l vs t^2 - -{{{ Pause here and try out the following exercises }}} - -%% 2 %% change the label on y-axis to "y" and save the lines of code - accordingly - -{{{ continue from paused state }}} - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial. -we have learnt - - * how to generate a least square fit - -{{{ 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 - - -.. - Local Variables: - mode: rst - indent-tabs-mode: nil - sentence-end-double-space: nil - fill-column: 75 - End: diff -r 88a01948450d -r d33698326409 lstsq/slides.org --- a/lstsq/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -#+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: Least square fit -#+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 - - Plotting a Least square fit line -* Summary - You should now be able to -- - - Plot a least square fit line. -* 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 88a01948450d -r d33698326409 lstsq/slides.tex --- a/lstsq/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,77 +0,0 @@ -% Created 2010-10-10 Sun 19:02 -\documentclass[presentation]{beamer} -\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\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}} - -\title{Least square fit} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Plotting a Least square fit line -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-2} - - You should now be able to -- -\begin{itemize} -\item Plot a least square fit line. -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-3} - - \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 88a01948450d -r d33698326409 manipulating-lists/questions.rst --- a/manipulating-lists/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,72 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. Given the list primes, ``primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, - 29]``, How do you obtain the last 4 primes? - - Answer: primes[-4:] - -#. Given the list primes, ``primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, - 29]``, What is the output of ``primes[::5]``? - - Answer: ``[2, 13]`` - -#. Given a list, p, of unknown length, obtain the first 3 (or all, if - there are fewer) characters of it. - - Answer: p[:3] - -#. The method ``reverse`` reverses a list in-place. True or False? - - Answer: True - -#. ``reversed`` function reverses a list in-place. True or False? - - Answer: False - -#. Given the list ``p = [1, 2, 3]``. p[4] produces an IndexError. True - or False? - - Answer: True - -#. Given the list ``p = [1, 2, 3]``. p[:4] produces an IndexError. True - or False? - - Answer: False - -#. Given the list primes, ``primes = [2, 3, 5, 7, 11]``, What is the - output of ``primes[::-1]``? - - Answer: [11, 7, 5, 3, 2] - -#. Given the list primes, ``primes = [2, 3, 5, 7, 11]``, What is the - output of ``primes[::-3]``? - - Answer: [11, 3] - - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -#. Given a list p. Append it's reverse to itself. - - Answer:: - - p = p + reversed(p) - - -#. Marks is a list containing the roll numbers of students followed by - marks. [This is not a recommended way to hold the marks details, - but the teacher knows only so much Python!] Now she wants to get - the average of the marks. Help her do it. - - Answer:: - - marks = [1, 9, 2, 8, 3, 3, 4, 10, 5, 2] - average = sum(marks[1::2])/len(marks[1::2]) - - diff -r 88a01948450d -r d33698326409 manipulating-lists/quickref.tex --- a/manipulating-lists/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,10 +0,0 @@ -Slicing \& Striding a list:\\ -{\ex \lstinline| A[start:stop:step]|} \lstinline|stop| excluded - -Sorting a list:\\ -{\ex \lstinline| sorted(A)|} -- returns new list -{\ex \lstinline| A.sort()|} -- in-place sort - -Reversing a list:\\ -{\ex \lstinline| A[::-1]|} -- returns new list -{\ex \lstinline| A.reverse()|} -- in-place reverse diff -r 88a01948450d -r d33698326409 manipulating-lists/script.rst --- a/manipulating-lists/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,238 +0,0 @@ -.. Objectives -.. ---------- - -.. Clearly state the objectives of the LO (along with RBT level) - -.. Prerequisites -.. ------------- - -.. 1. getting started with lists -.. 2. -.. 3. - -.. Author : Madhu - Internal Reviewer : Punch - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <16-11-2010, Anand, OK> [2010-10-05] - -Script ------- - -{{{ Show the slide containing the title }}} - -Hello friends. Welcome to this spoken tutorial on Manipulating Lists. - -{{{ Show the slide containing the outline }}} - -We have already learnt about Lists in Python. In this tutorial, -we will learn about more advanced features of Lists in Python like how -to concatenate two lists, details of slicing and striding of lists, -methods to sort and reverse lists. - -{{{ Shift to terminal and start ipython }}} - -To begin with let us start ipython, by typing:: - - ipython - -on the terminal - -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. - -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 -or what we call as a slice of the list? Python supports slicing on -lists. Let us say I have the list:: - - primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] - -To obtain all the primes between 10 and 20 from the above list of -primes we say:: - - primes[4:8] - -This gives us all the elements in the list starting from the element -with the index 4, which is 11 in our list, upto the element with index 8 -in the list but not including the eigth element. So we obtain a slice -starting from 11 upto 19th. It is a very important to remember that -whenever we specify a range of elements in Python the start index is -included and end index is not included. So in the above case, 11 which -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 - -{{{ Show the slide containing p[start:stop] }}} - -By default the slice fetches all the elements between start and stop -including start but not stop. So as to say we obtain all the elements -between start and stop in steps of one. Python also provides us the -functionality to specify the steps in which the slice must be -obtained. Say we have:: - - 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 -steps of 2:: - - num[1:10:2] - -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:: - - num[:10] - -This gives us all the elements from the beginning upto the 10th -element but not including the 10th element in the list "num". Similary -if the stop index is not specified it is implicitly assumed to be the -end of the list, including the last element of the list:: - - num[10:] - -gives all the elements starting from the 10th element in the list -"num" upto the final element including that last element. Now:: - - num[::2] - -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 lists is concatenation -of two or more lists. We can combine two lists by using the "plus" -operator. Say we have - -{{{ Read as you type }}}:: - - a = [1, 2, 3, 4] - b = [4, 5, 6, 7] - a + b - -When we concatenate lists using the "plus" operator we get a new -list. We can store this list in a new variable:: - - c = a + b - c - -It is important to observe that the "plus" operator always returns a -new list without altering the lists being concatenated in any way. - -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:: - - a - [1, 5, 6, 7, 7, 10] - -As the sort method sorts the elements of a list, the original list we had -is overwritten or replaced. We have no way to obtain the original list -back. One way to avoid this is to keep a copy of the original list in -another variable and run the sort method on the list. However Python -also provides a built-in function called sorted which sorts the list -which is passed as an argument to it and returns a new sorted list:: - - a = [5, 1, 6, 7, 7, 10] - sorted(a) - -We can store this sorted list another list variable:: - - sa = sorted(a) - -Python also provides the reverse method which reverses -the list inplace:: - - a = [1, 2, 3, 4, 5] - a.reverse() - -reverses the list "a" and stores the reversed list inplace i.e. in "a" -itself. Lets see the list "a":: - - a - [5, 4, 3, 2, 1] - -But again the original list is lost. -.. #[punch: removed reversed, since it returns an iterator] - -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 - - * Obtaining parts of lists using slicing and striding - * List concatenation - * Sorting lists - * Reversing lists - -{{{ 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 88a01948450d -r d33698326409 manipulating-lists/slides.org --- a/manipulating-lists/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -#+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: Manipulating Lists -#+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 -#+STARTUP: align fold nodlcheck hidestars oddeven lognotestate - -* Outline - In this session we shall be looking at - - Concatenating lists - - Obtaining parts of lists - - Sorting lists - - Reversing lists -* Question 1 - Obtain the primes less than 10, from the list ~primes~. -* Solution 1 - #+begin_src python - 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 - Obtain all the multiples of three from the list ~num~. -* Solution 2 - #+begin_src python - num[::3] - #+end_src python -* Question 3 - 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 - sorted(marks)[::-1] - #+end_src python -OR - #+begin_src python - sorted(marks, reverse=True) - #+end_src python - -* Summary - 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}{} - \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 88a01948450d -r d33698326409 manipulating-lists/slides.tex --- a/manipulating-lists/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,152 +0,0 @@ -% Created 2010-11-09 Tue 16:07 -\documentclass[presentation]{beamer} -\usepackage[latin1]{inputenc} -\usepackage[T1]{fontenc} -\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}} - -\title{Manipulating Lists} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\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{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} - - 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{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{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 - \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 88a01948450d -r d33698326409 manipulating-strings/questions.rst --- a/manipulating-strings/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. Given the list week:: - - ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] - - ``"Sun" in week`` returns True or False? - - Answer: False - -#. Given the string ``s = "palindrome"``, what is returned by s[4:] - - Answer: ``ndrome`` - -#. Given the string ``s = "palindrome"``, what is returned by s[-4] - - Answer: ``r`` - -#. Given the string ``s = "palindrome"``, what is returned by s[4::-1] - - Answer: ``nilap`` - -#. Given the string ``s = "palindrome"``, what is returned by s[-4:] - - Answer: ``rome`` - -#. Given a string ``s = "this is a string"``, how will you change it - to ``"this isn't a list"`` ? - - Answer:: - - s = s.replace("string", "list") - s = s.replace("is", "isn't") - -#. Given a string ``s = "this is a string"``, how will you change it - to ``"THIS ISN'T A LIST"`` ? - - Answer:: - - s = s.replace("string", "list") - s = s.replace("is", "isn't") - s = s.upper() - -#. Given a line from a CSV file (comma separated values), convert it - to a space separated line. - - Answer: line.replace(',', ' ') - -#. Given the string "F.R.I.E.N.D.S" in s, obtain the "friends". - - Answer: ``s[::2].lower()`` - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Given the string friends, obtain the string "F.R.I.E.N.D.S". - - Answer:: - - s = "friends" - s = s.upper() - s_list = list(s) - ".".join(s_list) - -2. Given a string with double quotes and single quotes. Interchange - all the double quotes to single quotes and vice-versa. [Solve it - for this particular string. Not a generic one. Solve it for a - generic string, if you know how to iterate over a list.] - - s = """ "Isn't this a 'simple' task?" "No, it isn't." "Yes! it is." """ - - Answer:: - - s = s.replace('"', '#') - s = s.replace("'", '"') - s = s.replace('#', "'") - - .. depends on ``for`` which is not an LO dependency a generic string. - - For generic string - Answer:: - - S = [] - s_list = s.split("'") - - for s_s in s_list: - S.append(s_s.replace('"', "'")) - - s = '"'.join(S) diff -r 88a01948450d -r d33698326409 manipulating-strings/quickref.tex --- a/manipulating-strings/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,14 +0,0 @@ -\textbf{Manipulating strings} - -String indexing starts from 0, like lists. - -\lstinline|s = `Hello World'|\\ -\lstinline|s[0:5]| gives \texttt{Hello}\\ -\lstinline|s[6:]| gives \textt{World}\\ -\lstinline|s[6::2]| gives \textt{Wrd}\\ - -\lstinline|s.replace('e', 'a')| returns a new string with all e's -replaced by a. - -\lstinline|s.lower()| and \lstinline|s.upper()| return new strings -with all lower and upper case letters, respectively. diff -r 88a01948450d -r d33698326409 manipulating-strings/script.rst --- a/manipulating-strings/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,255 +0,0 @@ -.. Objectives -.. ---------- - -.. By the end of this tutorial, you will be able to - -.. 1. Slice strings and get sub-strings out of them -.. #. Reverse strings -.. #. Replace characters in strings. -.. #. Convert strings to upper or lower case -.. #. joining a list of strings - -.. Prerequisites -.. ------------- - -.. 1. getting started with strings -.. #. getting started with lists -.. #. basic datatypes - -.. Author : Puneeth - Internal Reviewer : Amit - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <08-11-2010, Anand, OK> [2010-10-05] - -Script ------- - -{{{ Show the slide containing title }}} - -Hello Friends. Welcome to this tutorial on manipulating strings. - -{{{ show the slide with outline }}} - -In this tutorial we shall learn to manipulate strings, specifically -slicing and reversing them, or replacing characters, converting from -upper to lower case and vice-versa and joining a list of strings. - -We have an ``ipython`` shell open, in which we are going to work, -through out this session. - -Let us consider a simple problem, and learn how to slice strings and -get sub-strings. - -Let's say the variable ``week`` has the list of the names of the days -of the week. - -:: - - week = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] - - -Now given a string ``s``, we should be able to check if the string is a -valid name of a day of the week or not. - -:: - - s = saturday - - -``s`` could be in any of the forms --- sat, saturday, Sat, Saturday, -SAT, SATURDAY. For now, shall now be solving the problem only for the forms, -sat and saturday. We shall solve it for the other forms, at the end of -the tutorial. - -{{{ show these forms in a slide }}} - -So, we need to check if the first three characters of the given string -exists in the variable ``week``. - -As, with any of the sequence data-types, strings can be sliced into -sub-strings. To get the first three characters of s, we say, - -:: - - s[0:3] - -Note that, we are slicing the string from the index 0 to index 3, 3 -not included. - -As we already know, the last element of the string can be accessed -using ``s[-1]``. - -Following is an exercise that you must do. - -%%1%% Obtain the sub-string excluding the first and last characters -from the string s. - -Please, pause the video here. Do the exercise(s) and then continue. - -:: - - s[1:-1] - -gives the substring of s, without the first and the last -characters of s. - -:: - - s = saturday - s[:3] - -Now, we just check if that substring is present in the variable -``week``. - -:: - - s[:3] in week - -Let us now consider the problem of finding out if a given string is -palindromic or not. First of all, a palindromic string is a string -that remains same even when it has been reversed. - -Let the string given be ``malayalam``. - -:: - - s = "malayalam" - -Now, we need to compare this string with it's reverse. - -Again, we will use a technique common to all sequence data-types, -[::-1] - -So, we obtain the reverse of s, by simply saying, - -:: - - s[::-1] - -Now, to check if the string is ``s`` is palindromic, we say -:: - - s == s[::-1] - -As, expected, we get ``True``. - -Now, if the string we are given is ``Malayalam`` instead of -``malayalam``, the above comparison would return a False. So, we will -have to convert the string to all lower case or all upper case, before -comparing. Python provides methods, ``s.lower`` and ``s.upper`` to -achieve this. - -Let's try it out. -:: - - s = "Malayalam" - - s.upper() - - s - -As you can see, s has not changed. It is because, ``upper`` returns a -new string. It doesn't change the original string. - -:: - - s.lower() - - s.lower() == s.lower()[::-1] - -Following is an exercise that you must do. - -%%2%% Check if ``s`` is a valid name of a day of the week. Change the -solution to this problem, to include forms like, SAT, SATURDAY, -Saturday and Sat. - -Please, pause the video here. Do the exercise and then continue. - -:: - - s in week - - s.lower()[:3] in week - - -So, as you can see, now we can check for presence of ``s`` in -``week``, in whichever format it is present -- capitalized, or all -caps, full name or short form. - -We just convert any input string to lower case and then check if it is -present in the list ``week``. - -Now, let us consider another problem. We often encounter e-mail id's -which have @ and periods replaced with text, something like -info[at]fossee[dot]in. We now wish to get back proper e-mail -addresses. - -Let's say the variable email has the email address. -:: - - email = "info[at]fossee[dot]in" - -Now, we first replace the ``[at]`` with the ``@``, using the replace -method of strings. -:: - - email = email.replace("[at]", "@") - print email - -Following is an exercise that you must do. - -%%3%% Replace the ``[dot]`` with ``.`` in ``email`` - -Please, pause the video here. Do the exercise and then continue. - -:: - - email = email.replace("[dot]", ".") - print email - -Now, let's look at another interesting problem where we have a list of -e-mail addresses and we wish to obtain one long string of e-mail -addresses separated by commas or semi-colons. - -:: - - email_list = ["info@fossee.in", "enquiries@fossee.in", "help@fossee.in"] - - -Now, if we wish to obtain one long string, separating each of the -email id by a comma, we use the join operator on ``,``. - -:: - - email_str = ", ".join(email_list) - print email_str - -Notice that the email ids are joined by a comma followed by a space. - -Following is an exercise that you must do. - -%%3%% From the email_str that we generated, change the separator to be -a semicolon instead of a comma. - -Please, pause the video here. Do the exercise and then continue. - -:: - - email_str = email_str.replace(",", ";") - -That brings us to the end of the tutorial. - -{{{ show summary slide }}} - -In this tutorial, we have learnt how to get substrings, reverse -strings and a few useful methods, namely upper, lower, replace and -join. - -{{{ 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 88a01948450d -r d33698326409 manipulating-strings/slides.org --- a/manipulating-strings/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -#+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: Manipulating strings -#+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 - - Slicing strings to get sub-strings - - Reversing strings - - Replacing characters in strings. - - Converting strings to upper or lower case - - Joining a list of strings -* Question 1 - Obtain the sub-string excluding the first and last characters from - the string ~s~. -* Solution 1 - #+begin_src python - In []: s[1:-1] - #+end_src -* Question 2 - Given a list week, week = ~week = ["sun", "mon", "tue", "wed", - "thu", "fri", "sat"]~. Check if ~s~ is a valid name of a day of the - week. Change the solution to this problem, to include forms like, - SAT, SATURDAY, Saturday and Sat. -* Solution 2 - #+begin_src python - In []: s in week - In []: s.lower()[:3] in week - #+end_src -* Question 3 - Given ~email~ -- ~info@fossee[dot]in~ - - Replace the ~[dot]~ with ~.~ in ~email~ -* Solution 3 - #+begin_src python - email.replace('[dot], '.') - print email - #+end_src -* Question 4 - From the ~email_str~ that we generated, change the separator to be a - semicolon instead of a comma. -* Solution 4 - #+begin_src python - email_str = email_str.replace(",", ";") - #+end_src -* Summary - You should now be able to -- - - Slice strings and get sub-strings out of them - - Reverse strings - - Replace characters in strings. - - Convert strings to upper or lower case - - Join a list of strings - -* 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 88a01948450d -r d33698326409 manipulating-strings/slides.tex --- a/manipulating-strings/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,150 +0,0 @@ -% Created 2010-10-28 Thu 11:35 -\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{Manipulating strings} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Slicing strings to get sub-strings -\item Reversing strings -\item Replacing characters in strings. -\item Converting strings to upper or lower case -\item Joining a list of strings -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Question 1} -\label{sec-2} - - Obtain the sub-string excluding the first and last characters from - the string \texttt{s}. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 1} -\label{sec-3} - -\begin{verbatim} -In []: s[1:-1] -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Question 2} -\label{sec-4} - - Given a list week, week = \texttt{week = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]}. Check if \texttt{s} is a valid name of a day of the - week. Change the solution to this problem, to include forms like, - SAT, SATURDAY, Saturday and Sat. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 2} -\label{sec-5} - -\begin{verbatim} -In []: s in week -In []: s.lower()[:3] in week -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Question 3} -\label{sec-6} - - Given \texttt{email} -- \texttt{info@fossee[dot]in} - - Replace the \texttt{[dot]} with \texttt{.} in \texttt{email} -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 3} -\label{sec-7} - -\begin{verbatim} -email.replace('[dot], '.') -print email -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Question 4} -\label{sec-8} - - From the \texttt{email\_str} that we generated, change the separator to be a - semicolon instead of a comma. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 4} -\label{sec-9} - -\begin{verbatim} -email_str = email_str.replace(",", ";") -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-10} - - You should now be able to -- -\begin{itemize} -\item Slice strings and get sub-strings out of them -\item Reverse strings -\item Replace characters in strings. -\item Convert strings to upper or lower case -\item Join a list of strings -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-11} - - \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 88a01948450d -r d33698326409 manipulating_lists/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating_lists/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,72 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Given the list primes, ``primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, + 29]``, How do you obtain the last 4 primes? + + Answer: primes[-4:] + +#. Given the list primes, ``primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, + 29]``, What is the output of ``primes[::5]``? + + Answer: ``[2, 13]`` + +#. Given a list, p, of unknown length, obtain the first 3 (or all, if + there are fewer) characters of it. + + Answer: p[:3] + +#. The method ``reverse`` reverses a list in-place. True or False? + + Answer: True + +#. ``reversed`` function reverses a list in-place. True or False? + + Answer: False + +#. Given the list ``p = [1, 2, 3]``. p[4] produces an IndexError. True + or False? + + Answer: True + +#. Given the list ``p = [1, 2, 3]``. p[:4] produces an IndexError. True + or False? + + Answer: False + +#. Given the list primes, ``primes = [2, 3, 5, 7, 11]``, What is the + output of ``primes[::-1]``? + + Answer: [11, 7, 5, 3, 2] + +#. Given the list primes, ``primes = [2, 3, 5, 7, 11]``, What is the + output of ``primes[::-3]``? + + Answer: [11, 3] + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +#. Given a list p. Append it's reverse to itself. + + Answer:: + + p = p + reversed(p) + + +#. Marks is a list containing the roll numbers of students followed by + marks. [This is not a recommended way to hold the marks details, + but the teacher knows only so much Python!] Now she wants to get + the average of the marks. Help her do it. + + Answer:: + + marks = [1, 9, 2, 8, 3, 3, 4, 10, 5, 2] + average = sum(marks[1::2])/len(marks[1::2]) + + diff -r 88a01948450d -r d33698326409 manipulating_lists/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating_lists/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,10 @@ +Slicing \& Striding a list:\\ +{\ex \lstinline| A[start:stop:step]|} \lstinline|stop| excluded + +Sorting a list:\\ +{\ex \lstinline| sorted(A)|} -- returns new list +{\ex \lstinline| A.sort()|} -- in-place sort + +Reversing a list:\\ +{\ex \lstinline| A[::-1]|} -- returns new list +{\ex \lstinline| A.reverse()|} -- in-place reverse diff -r 88a01948450d -r d33698326409 manipulating_lists/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating_lists/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,238 @@ +.. Objectives +.. ---------- + +.. Clearly state the objectives of the LO (along with RBT level) + +.. Prerequisites +.. ------------- + +.. 1. getting started with lists +.. 2. +.. 3. + +.. Author : Madhu + Internal Reviewer : Punch + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <16-11-2010, Anand, OK> [2010-10-05] + +Script +------ + +{{{ Show the slide containing the title }}} + +Hello friends. Welcome to this spoken tutorial on Manipulating Lists. + +{{{ Show the slide containing the outline }}} + +We have already learnt about Lists in Python. In this tutorial, +we will learn about more advanced features of Lists in Python like how +to concatenate two lists, details of slicing and striding of lists, +methods to sort and reverse lists. + +{{{ Shift to terminal and start ipython }}} + +To begin with let us start ipython, by typing:: + + ipython + +on the terminal + +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. + +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 +or what we call as a slice of the list? Python supports slicing on +lists. Let us say I have the list:: + + primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + +To obtain all the primes between 10 and 20 from the above list of +primes we say:: + + primes[4:8] + +This gives us all the elements in the list starting from the element +with the index 4, which is 11 in our list, upto the element with index 8 +in the list but not including the eigth element. So we obtain a slice +starting from 11 upto 19th. It is a very important to remember that +whenever we specify a range of elements in Python the start index is +included and end index is not included. So in the above case, 11 which +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 + +{{{ Show the slide containing p[start:stop] }}} + +By default the slice fetches all the elements between start and stop +including start but not stop. So as to say we obtain all the elements +between start and stop in steps of one. Python also provides us the +functionality to specify the steps in which the slice must be +obtained. Say we have:: + + 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 +steps of 2:: + + num[1:10:2] + +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:: + + num[:10] + +This gives us all the elements from the beginning upto the 10th +element but not including the 10th element in the list "num". Similary +if the stop index is not specified it is implicitly assumed to be the +end of the list, including the last element of the list:: + + num[10:] + +gives all the elements starting from the 10th element in the list +"num" upto the final element including that last element. Now:: + + num[::2] + +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 lists is concatenation +of two or more lists. We can combine two lists by using the "plus" +operator. Say we have + +{{{ Read as you type }}}:: + + a = [1, 2, 3, 4] + b = [4, 5, 6, 7] + a + b + +When we concatenate lists using the "plus" operator we get a new +list. We can store this list in a new variable:: + + c = a + b + c + +It is important to observe that the "plus" operator always returns a +new list without altering the lists being concatenated in any way. + +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:: + + a + [1, 5, 6, 7, 7, 10] + +As the sort method sorts the elements of a list, the original list we had +is overwritten or replaced. We have no way to obtain the original list +back. One way to avoid this is to keep a copy of the original list in +another variable and run the sort method on the list. However Python +also provides a built-in function called sorted which sorts the list +which is passed as an argument to it and returns a new sorted list:: + + a = [5, 1, 6, 7, 7, 10] + sorted(a) + +We can store this sorted list another list variable:: + + sa = sorted(a) + +Python also provides the reverse method which reverses +the list inplace:: + + a = [1, 2, 3, 4, 5] + a.reverse() + +reverses the list "a" and stores the reversed list inplace i.e. in "a" +itself. Lets see the list "a":: + + a + [5, 4, 3, 2, 1] + +But again the original list is lost. +.. #[punch: removed reversed, since it returns an iterator] + +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 + + * Obtaining parts of lists using slicing and striding + * List concatenation + * Sorting lists + * Reversing lists + +{{{ 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 88a01948450d -r d33698326409 manipulating_lists/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating_lists/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,94 @@ +#+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: Manipulating Lists +#+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 +#+STARTUP: align fold nodlcheck hidestars oddeven lognotestate + +* Outline + In this session we shall be looking at + - Concatenating lists + - Obtaining parts of lists + - Sorting lists + - Reversing lists +* Question 1 + Obtain the primes less than 10, from the list ~primes~. +* Solution 1 + #+begin_src python + 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 + Obtain all the multiples of three from the list ~num~. +* Solution 2 + #+begin_src python + num[::3] + #+end_src python +* Question 3 + 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 + sorted(marks)[::-1] + #+end_src python +OR + #+begin_src python + sorted(marks, reverse=True) + #+end_src python + +* Summary + 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}{} + \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 88a01948450d -r d33698326409 manipulating_lists/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating_lists/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,152 @@ +% Created 2010-11-09 Tue 16:07 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\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}} + +\title{Manipulating Lists} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\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{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} + + 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{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{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 + \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 88a01948450d -r d33698326409 manipulating_strings/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating_strings/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,94 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Given the list week:: + + ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] + + ``"Sun" in week`` returns True or False? + + Answer: False + +#. Given the string ``s = "palindrome"``, what is returned by s[4:] + + Answer: ``ndrome`` + +#. Given the string ``s = "palindrome"``, what is returned by s[-4] + + Answer: ``r`` + +#. Given the string ``s = "palindrome"``, what is returned by s[4::-1] + + Answer: ``nilap`` + +#. Given the string ``s = "palindrome"``, what is returned by s[-4:] + + Answer: ``rome`` + +#. Given a string ``s = "this is a string"``, how will you change it + to ``"this isn't a list"`` ? + + Answer:: + + s = s.replace("string", "list") + s = s.replace("is", "isn't") + +#. Given a string ``s = "this is a string"``, how will you change it + to ``"THIS ISN'T A LIST"`` ? + + Answer:: + + s = s.replace("string", "list") + s = s.replace("is", "isn't") + s = s.upper() + +#. Given a line from a CSV file (comma separated values), convert it + to a space separated line. + + Answer: line.replace(',', ' ') + +#. Given the string "F.R.I.E.N.D.S" in s, obtain the "friends". + + Answer: ``s[::2].lower()`` + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Given the string friends, obtain the string "F.R.I.E.N.D.S". + + Answer:: + + s = "friends" + s = s.upper() + s_list = list(s) + ".".join(s_list) + +2. Given a string with double quotes and single quotes. Interchange + all the double quotes to single quotes and vice-versa. [Solve it + for this particular string. Not a generic one. Solve it for a + generic string, if you know how to iterate over a list.] + + s = """ "Isn't this a 'simple' task?" "No, it isn't." "Yes! it is." """ + + Answer:: + + s = s.replace('"', '#') + s = s.replace("'", '"') + s = s.replace('#', "'") + + .. depends on ``for`` which is not an LO dependency a generic string. + + For generic string + Answer:: + + S = [] + s_list = s.split("'") + + for s_s in s_list: + S.append(s_s.replace('"', "'")) + + s = '"'.join(S) diff -r 88a01948450d -r d33698326409 manipulating_strings/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating_strings/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,14 @@ +\textbf{Manipulating strings} + +String indexing starts from 0, like lists. + +\lstinline|s = `Hello World'|\\ +\lstinline|s[0:5]| gives \texttt{Hello}\\ +\lstinline|s[6:]| gives \textt{World}\\ +\lstinline|s[6::2]| gives \textt{Wrd}\\ + +\lstinline|s.replace('e', 'a')| returns a new string with all e's +replaced by a. + +\lstinline|s.lower()| and \lstinline|s.upper()| return new strings +with all lower and upper case letters, respectively. diff -r 88a01948450d -r d33698326409 manipulating_strings/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating_strings/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,255 @@ +.. Objectives +.. ---------- + +.. By the end of this tutorial, you will be able to + +.. 1. Slice strings and get sub-strings out of them +.. #. Reverse strings +.. #. Replace characters in strings. +.. #. Convert strings to upper or lower case +.. #. joining a list of strings + +.. Prerequisites +.. ------------- + +.. 1. getting started with strings +.. #. getting started with lists +.. #. basic datatypes + +.. Author : Puneeth + Internal Reviewer : Amit + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <08-11-2010, Anand, OK> [2010-10-05] + +Script +------ + +{{{ Show the slide containing title }}} + +Hello Friends. Welcome to this tutorial on manipulating strings. + +{{{ show the slide with outline }}} + +In this tutorial we shall learn to manipulate strings, specifically +slicing and reversing them, or replacing characters, converting from +upper to lower case and vice-versa and joining a list of strings. + +We have an ``ipython`` shell open, in which we are going to work, +through out this session. + +Let us consider a simple problem, and learn how to slice strings and +get sub-strings. + +Let's say the variable ``week`` has the list of the names of the days +of the week. + +:: + + week = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] + + +Now given a string ``s``, we should be able to check if the string is a +valid name of a day of the week or not. + +:: + + s = saturday + + +``s`` could be in any of the forms --- sat, saturday, Sat, Saturday, +SAT, SATURDAY. For now, shall now be solving the problem only for the forms, +sat and saturday. We shall solve it for the other forms, at the end of +the tutorial. + +{{{ show these forms in a slide }}} + +So, we need to check if the first three characters of the given string +exists in the variable ``week``. + +As, with any of the sequence data-types, strings can be sliced into +sub-strings. To get the first three characters of s, we say, + +:: + + s[0:3] + +Note that, we are slicing the string from the index 0 to index 3, 3 +not included. + +As we already know, the last element of the string can be accessed +using ``s[-1]``. + +Following is an exercise that you must do. + +%%1%% Obtain the sub-string excluding the first and last characters +from the string s. + +Please, pause the video here. Do the exercise(s) and then continue. + +:: + + s[1:-1] + +gives the substring of s, without the first and the last +characters of s. + +:: + + s = saturday + s[:3] + +Now, we just check if that substring is present in the variable +``week``. + +:: + + s[:3] in week + +Let us now consider the problem of finding out if a given string is +palindromic or not. First of all, a palindromic string is a string +that remains same even when it has been reversed. + +Let the string given be ``malayalam``. + +:: + + s = "malayalam" + +Now, we need to compare this string with it's reverse. + +Again, we will use a technique common to all sequence data-types, +[::-1] + +So, we obtain the reverse of s, by simply saying, + +:: + + s[::-1] + +Now, to check if the string is ``s`` is palindromic, we say +:: + + s == s[::-1] + +As, expected, we get ``True``. + +Now, if the string we are given is ``Malayalam`` instead of +``malayalam``, the above comparison would return a False. So, we will +have to convert the string to all lower case or all upper case, before +comparing. Python provides methods, ``s.lower`` and ``s.upper`` to +achieve this. + +Let's try it out. +:: + + s = "Malayalam" + + s.upper() + + s + +As you can see, s has not changed. It is because, ``upper`` returns a +new string. It doesn't change the original string. + +:: + + s.lower() + + s.lower() == s.lower()[::-1] + +Following is an exercise that you must do. + +%%2%% Check if ``s`` is a valid name of a day of the week. Change the +solution to this problem, to include forms like, SAT, SATURDAY, +Saturday and Sat. + +Please, pause the video here. Do the exercise and then continue. + +:: + + s in week + + s.lower()[:3] in week + + +So, as you can see, now we can check for presence of ``s`` in +``week``, in whichever format it is present -- capitalized, or all +caps, full name or short form. + +We just convert any input string to lower case and then check if it is +present in the list ``week``. + +Now, let us consider another problem. We often encounter e-mail id's +which have @ and periods replaced with text, something like +info[at]fossee[dot]in. We now wish to get back proper e-mail +addresses. + +Let's say the variable email has the email address. +:: + + email = "info[at]fossee[dot]in" + +Now, we first replace the ``[at]`` with the ``@``, using the replace +method of strings. +:: + + email = email.replace("[at]", "@") + print email + +Following is an exercise that you must do. + +%%3%% Replace the ``[dot]`` with ``.`` in ``email`` + +Please, pause the video here. Do the exercise and then continue. + +:: + + email = email.replace("[dot]", ".") + print email + +Now, let's look at another interesting problem where we have a list of +e-mail addresses and we wish to obtain one long string of e-mail +addresses separated by commas or semi-colons. + +:: + + email_list = ["info@fossee.in", "enquiries@fossee.in", "help@fossee.in"] + + +Now, if we wish to obtain one long string, separating each of the +email id by a comma, we use the join operator on ``,``. + +:: + + email_str = ", ".join(email_list) + print email_str + +Notice that the email ids are joined by a comma followed by a space. + +Following is an exercise that you must do. + +%%3%% From the email_str that we generated, change the separator to be +a semicolon instead of a comma. + +Please, pause the video here. Do the exercise and then continue. + +:: + + email_str = email_str.replace(",", ";") + +That brings us to the end of the tutorial. + +{{{ show summary slide }}} + +In this tutorial, we have learnt how to get substrings, reverse +strings and a few useful methods, namely upper, lower, replace and +join. + +{{{ 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 88a01948450d -r d33698326409 manipulating_strings/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating_strings/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,94 @@ +#+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: Manipulating strings +#+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 + - Slicing strings to get sub-strings + - Reversing strings + - Replacing characters in strings. + - Converting strings to upper or lower case + - Joining a list of strings +* Question 1 + Obtain the sub-string excluding the first and last characters from + the string ~s~. +* Solution 1 + #+begin_src python + In []: s[1:-1] + #+end_src +* Question 2 + Given a list week, week = ~week = ["sun", "mon", "tue", "wed", + "thu", "fri", "sat"]~. Check if ~s~ is a valid name of a day of the + week. Change the solution to this problem, to include forms like, + SAT, SATURDAY, Saturday and Sat. +* Solution 2 + #+begin_src python + In []: s in week + In []: s.lower()[:3] in week + #+end_src +* Question 3 + Given ~email~ -- ~info@fossee[dot]in~ + + Replace the ~[dot]~ with ~.~ in ~email~ +* Solution 3 + #+begin_src python + email.replace('[dot], '.') + print email + #+end_src +* Question 4 + From the ~email_str~ that we generated, change the separator to be a + semicolon instead of a comma. +* Solution 4 + #+begin_src python + email_str = email_str.replace(",", ";") + #+end_src +* Summary + You should now be able to -- + - Slice strings and get sub-strings out of them + - Reverse strings + - Replace characters in strings. + - Convert strings to upper or lower case + - Join a list of strings + +* 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 88a01948450d -r d33698326409 manipulating_strings/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating_strings/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,150 @@ +% Created 2010-10-28 Thu 11:35 +\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{Manipulating strings} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Slicing strings to get sub-strings +\item Reversing strings +\item Replacing characters in strings. +\item Converting strings to upper or lower case +\item Joining a list of strings +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Obtain the sub-string excluding the first and last characters from + the string \texttt{s}. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-3} + +\begin{verbatim} +In []: s[1:-1] +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + Given a list week, week = \texttt{week = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]}. Check if \texttt{s} is a valid name of a day of the + week. Change the solution to this problem, to include forms like, + SAT, SATURDAY, Saturday and Sat. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} + +\begin{verbatim} +In []: s in week +In []: s.lower()[:3] in week +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + + Given \texttt{email} -- \texttt{info@fossee[dot]in} + + Replace the \texttt{[dot]} with \texttt{.} in \texttt{email} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 3} +\label{sec-7} + +\begin{verbatim} +email.replace('[dot], '.') +print email +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-8} + + From the \texttt{email\_str} that we generated, change the separator to be a + semicolon instead of a comma. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 4} +\label{sec-9} + +\begin{verbatim} +email_str = email_str.replace(",", ";") +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-10} + + You should now be able to -- +\begin{itemize} +\item Slice strings and get sub-strings out of them +\item Reverse strings +\item Replace characters in strings. +\item Convert strings to upper or lower case +\item Join a list of strings +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-11} + + \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 88a01948450d -r d33698326409 module-assessment-arrays-matrices.rst --- a/module-assessment-arrays-matrices.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,92 +0,0 @@ -======== - Script -======== - -Welcome. - -This spoken tutorial is a self-assessment tutorial and you will be -able to assess yourself on the concepts learnt in the Module on Arrays -and Matrices. - - -As with all other assessments we will first start with a few short -questions that will not take you more that 15 to 20 seconds to -answer. Then we shall move on to a bigger problem, that you are -expected to solve in less than 10 mins. - - - * Given a list of marks:: - - marks = [10, 20, 30, 50, 55, 75, 83] - - How will you convert it to an array? - - * What is the shape of the following array?:: - - x = array([[1,2,3,4], - [3,4,2,5]]) - - * What is the resulting array:: - - a = array([[1, 2], - [3, 4]]) - - a[1,0] = 0 - - * What is the resulting array?:: - - x = array(([1,2,3,4], - [2,3,4,5])) - - x[-2][-3] = 4 - - - * How do we change the array ``x = array([[1,2,3,4]])`` to - ``array([[1,2,0,4]])``? - - * How do we get the slice:: - - array([[2,3], - [4,2]]) - - out of the array:: - - x = array([[1,2,3,4], - [3,4,2,5]]) - - - * What is the output of x[::3,::3], when x is:: - - x = array([[9,18,27], - [30,60,90], - [14,7,1]]) - - * How do you get the transpose of this array?:: - - a = array([[1, 2], - [3, 4]]) - - * What is the output of the following?:: - - a = array([[1, 2], - [3, 4]]) - - b = array([[1, 1], - [2, 2]]) - - a*b - - -{{{ show slides with solutions to these problems }}} - -Now, let us move on to a larger problem. From the image -`tagore-einstein.png`` - - + extract the face of Einstein alone. - + extract the face of Tagore alone. - + get a smaller copy of the image, that is a fourth it's size. - - -{{{ show slide with solutions to the problem }}} - -Thank You! diff -r 88a01948450d -r d33698326409 module_assessment_arrays_matrices.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/module_assessment_arrays_matrices.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,92 @@ +======== + Script +======== + +Welcome. + +This spoken tutorial is a self-assessment tutorial and you will be +able to assess yourself on the concepts learnt in the Module on Arrays +and Matrices. + + +As with all other assessments we will first start with a few short +questions that will not take you more that 15 to 20 seconds to +answer. Then we shall move on to a bigger problem, that you are +expected to solve in less than 10 mins. + + + * Given a list of marks:: + + marks = [10, 20, 30, 50, 55, 75, 83] + + How will you convert it to an array? + + * What is the shape of the following array?:: + + x = array([[1,2,3,4], + [3,4,2,5]]) + + * What is the resulting array:: + + a = array([[1, 2], + [3, 4]]) + + a[1,0] = 0 + + * What is the resulting array?:: + + x = array(([1,2,3,4], + [2,3,4,5])) + + x[-2][-3] = 4 + + + * How do we change the array ``x = array([[1,2,3,4]])`` to + ``array([[1,2,0,4]])``? + + * How do we get the slice:: + + array([[2,3], + [4,2]]) + + out of the array:: + + x = array([[1,2,3,4], + [3,4,2,5]]) + + + * What is the output of x[::3,::3], when x is:: + + x = array([[9,18,27], + [30,60,90], + [14,7,1]]) + + * How do you get the transpose of this array?:: + + a = array([[1, 2], + [3, 4]]) + + * What is the output of the following?:: + + a = array([[1, 2], + [3, 4]]) + + b = array([[1, 1], + [2, 2]]) + + a*b + + +{{{ show slides with solutions to these problems }}} + +Now, let us move on to a larger problem. From the image +`tagore-einstein.png`` + + + extract the face of Einstein alone. + + extract the face of Tagore alone. + + get a smaller copy of the image, that is a fourth it's size. + + +{{{ show slide with solutions to the problem }}} + +Thank You! diff -r 88a01948450d -r d33698326409 multiple-plots/questions.rst --- a/multiple-plots/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,89 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. Multiple plots appear in different figures by default. True or False? - - Answer: False - -#. What command is used to get individual plots separately? - - Answer: Figure - -#. Which figure is closed after the following commands are run? - -:: - - x = linspace(0, 50, 500) - figure(1) - plot(x, sin(x), 'b') - figure(2) - plot(x, cos(x), 'g') - xlabel('x') - ylabel('cos(x)') - close() - - Answer: Figure 2 - -#. Describe the plot obtained by the following commands:: - - x = linspace(0, 50, 500) - subplot(2, 1, 1) - plot(x, sin(x), 'b') - -Answer: A figure window with space for 2 plots one below the other is - obtained. The sine plot with blue line appears in the first row. - -#. Describe the plot obtained by the following commands:: - - x = linspace(0, 50, 500) - subplot(2, 1, 1) - plot(x, sin(x), 'b') - subplot(2, 1, 2) - plot(x, cos(x), 'g') - - Answer: 2 plots one below another. sine in blue on first row. cosine - in green in the second row. - -#. Describe the plot obtained by the following commands:: - - x = linspace(0, 50, 500) - subplot(2, 1, 1) - plot(x, sin(x), 'b') - subplot(2, 1, 2) - plot(x, cos(x), 'g') - subplot(2, 1, 1) - plot(x, tan(x), 'r') - - Answer: 2 plots one below another. tan in red on first row. cosine - in green in the second row. - - -#. Which of the following gives the correct legend for the commands below - - a. legend([sin, cos, tan]) - #. legend([tan, cos, sin]) - #. legend[(tan, cos, sin)] - #. legend(['sin', 'cos', 'tan']) - #. legend(['tan', 'cos', 'sin']) - -:: - - x = linspace(0, 50, 500) - figure(1) - plot(x, sin(x), 'b') - figure(2) - plot(x, cos(x), 'g') - figure(3) - plot(x, tan(x), 'b') - - Answer: legend(['tan', 'cos', 'sin']) - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Question 1 -2. Question 2 diff -r 88a01948450d -r d33698326409 multiple-plots/script.rst --- a/multiple-plots/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,386 +0,0 @@ -.. Objectives -.. ---------- - -.. * How to draw multiple plots which are overlaid -.. * the figure command -.. * the legend command -.. * how to switch between the plots and perform some operations on each -.. of them like saving the plots and -.. * creating and switching between subplots - - -.. Prerequisites -.. ------------- - -.. 1. using the plot command interactively -.. 2. embellishing a plot -.. 3. saving plots - -.. Author : Madhu - Internal Reviewer 1 : [potential reviewer: Puneeth] - Internal Reviewer 2 : Nishanth - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <, not OK> [] - - -Script ------- - -{{{ Show the slide containing the title }}} - -Hello friends. Welcome to this spoken tutorial on Multiple plots. - -{{{ Show the slide containing the outline }}} - -In this tutorial, we will learn how to draw more than one plot, how to -add legends to each plot to indicate what each plot represents. We -will also learn how to switch between the plots and create multiple -plots with different regular axes which are also called as subplots. - -.. #[Nishanth]: See diff - edited a grammatical mistake -.. #[Madhu: Done] - -{{{ Shift to terminal and start ipython -pylab }}} - -To begin with let us start ipython with pylab, by typing:: - - ipython -pylab - -on the terminal - -Let us first create set of points for our plot. For this we will use -the command called linspace:: - - x = linspace(0, 50, 10) - -linspace command creates 10 points in the interval between 0 and 50 -both inclusive. We assign these values to a variable called x. - -.. #[Nishanth]: pre requisite for this LO is basic plotting which - covers linspace and plot. So you may not need to - specify all that again. But not a problem if it is - there also. -.. #[Madhu: Since I thought the LOs are disconnected, I thought it is - better to give a very short intro to it] - -Now let us draw a plot simple sine plot using these points:: - - plot(x, sin(x)) - -This should give us a nice sine plot. - -{{{ Switch to the plot window }}} - -Oh! wait! Is that a nice sine plot? Does a sine plot actually look -like that? We know that a sine plot is a smooth curve. Is it not? What -really caused this? - -.. #[Nishanth]: See diff -.. #[Madhu: Done] - -{{{ pause for a while }}} - -A small investigation on linspace tells us that we chose too few -points in a large interval between 0 and 50 for the curve to be -smooth. This should also indicate that the plot command actually plots -the set of points given by x and sin(x) and it doesn't plot the -analytical function itself i.e. it plots the points given by -Analytical functions. So now let us use linspace again to get 500 -points between 0 and 100 and draw the sine plot - -.. #[Nishanth]: Here specify that when we do plot(x, sin(x) - it is actually plotting two sets of points - and not analytical functions. Hence the sharp - curve. -.. #[Madhu: Incorporated] - -{{{ Switch to ipython andtype }}} :: - - y = linspace(0, 50, 500) - plot(y, sin(y)) - -{{{ Change to the plot window }}} - -Now we see what we remember as a sine plot. A smooth curve. If we -carefully notice we also have two plots now one overlaid upon -another. In pylab, by default all the plots are overlaid. - -Since we have two plots now overlaid upon each other we would like to -have a way to indicate what each plot represents to distinguish -between them. This is accomplished using legends. Equivalently, the -legend command does this for us - -{{{ Switch to ipython }}}:: - - legend(['sin(x)', 'cos(x)']) - -.. #[Nishanth]: This legend may go up in the script. May be before - introducing the figure command itself. -.. #[Madhu: brought up] - -The legend command takes a single list of parameters where each -parameter is the text indicating the plots in the order of their -serial number. - -{{{ Switch to plot window }}} - -Now we can see the legends being displayed for the respective sine and -cosine plots on the plot area. - -We have learnt quite a lot of things now, so let us take up an -exercise problem. - -%% 1 %% Draw two plots overlaid upon each other, with the first plot - being a parabola of the form y = 4(x ^ 2) and the second being a - straight line of the form y = 2x + 3 in the interval -5 to 5. Use - colors to differentiate between the plots and use legends to - indicate what each plot is doing. - -{{{ pause for a while and continue from paused state }}} - -We can obtain the two plots in different colors using the following -commands:: - - x = linspace(-5, 5, 100) - plot(x, 4 * (x * x), 'b') - plot(x, (2 * x) + 3, 'g') - -Now we can use the legend command as:: - - legend(['Parabola', 'Straight Line']) - -Or we can also just give the equations of the plot:: - - legend(['y = 4(x ^ 2)', 'y = 2x + 3']) - -We now know how to draw multiple plots and use legends to indicate -which plot represents what function, but we would like to have more -control over the plots we draw. Like switch between them, perform some -operations or labelling on them individually and so on. Let us see how -to accomplish this. Before we move on, let us clear our screen. - -{{{ Switch to ipython }}}:: - - clf() - -To accomplishing more control over individual plots we use the figure -command:: - - x = linspace(0, 50, 500) - figure(1) - plot(x, sin(x), 'b') - figure(2) - plot(x, cos(x), 'g') - -{{{ Switch to plot window }}} - -Now we have two plots, a sine plot and a cosine plot in two different -figures. - -.. #[Nishanth]: figure(1) and figure(2) give two different plots. - The remaining script moves on the fact that they - give overlaid plots which is not the case. - So clear the figure and plot cos and sin without - introducing figure command. Then introduce legend - and finish off the everything on legend. - Then introduce figure command. - -.. #[Madhu: I have just moved up the text about legend command. I - think that should take care of what you suggested. If there is - some mistake with it, Punch please let me know in your next - review.] - -{{{ Have both plot window and ipython side by side }}} - -The figure command takes an integer as an argument which is the serial -number of the plot. This selects the corresponding plot. All the plot -commands we run after this are applied to the selected plot. In this -example figure 1 is the sine plot and figure 2 is the cosine plot. We -can, for example, save each plot separately - -{{{ Switch to ipython }}}:: - - savefig('/home/user/cosine.png') - figure(1) - title('sin(y)') - savefig('/home/user/sine.png') - -{{{ Have both plot window and ipython side by side }}} - -We also titled our first plot as 'sin(y)' which we did not do for -the second plot. - -Let us attempt another exercise problem - -%% 2 %% Draw a line of the form y = x as one figure and another line - of the form y = 2x + 3. Switch back to the first figure, annotate - the x and y intercepts. Now switch to the second figure and - annotate its x and y intercepts. Save each of them. - -{{{ Pause for a while and continue from the paused state }}} - -To solve this problem we should first create the first figure using -the figure command. Before that, let us first run clf command to make -sure all the previous plots are cleared:: - - clf() - figure(1) - x = linspace(-5, 5, 100) - plot(x, x) - -Now we can use figure command to create second plotting area and plot -the figure:: - - figure(2) - plot(x, ((2 * x) + 3)) - -Now to switch between the figures we can use figure command. So let us -switch to figure 1. We are asked to annotate x and y intercepts of the -figure 1 but since figure 1 passes through origin we will have to -annotate the origin. We will annotate the intercepts for the second -figure and save them as follows:: - - figure(1) - annotate('Origin', xy=(0.0, 0.0) - figure(2) - annotate('x-intercept', xy=(0, 3)) - annotate('y-intercept', xy=(0, -1.5)) - savefig('/home/fossee/plot2.png') - figure(1) - savefig('/home/fossee/plot1.png') - -At times we run into situations where we want to compare two plots and -in such cases we want to draw both the plots in the same plotting -area. The situation is such that the two plots have different regular -axes which means we cannot draw overlaid plots. In such cases we can -draw subplots. - -We use subplot command to accomplish this - -{{{ Switch to ipython }}}:: - - subplot(2, 1, 1) - -subplot command takes three arguments, the first being the number of -rows of subplots that must be created, - -{{{ Have both plot window and ipython side by side }}} - -in this case we have 2 as the first argument so it spilts the plotting area horizontally for -two subplots. The second argument specifies the number of coloumns of -subplots that must be created. We passed 1 as the argument so the -plotting area won't be split vertically and the last argument -specifies what subplot must be created now in the order of the serial -number. In this case we passed 1 as the argument, so the first subplot -that is top half is created. If we execute the subplot command as - -{{{ Switch to ipython }}}:: - - subplot(2, 1, 2) - -{{{ Switch to plot window }}} - -The lower subplot is created. Now we can draw plots in each of the -subplot area using the plot command. - -{{{ Switch to ipython }}}:: - - x = linspace(0, 50, 500) - plot(x, cos(x)) - subplot(2, 1, 1) - y = linspace(0, 5, 100) - plot(y, y ** 2) - -{{{ Have both plot window and ipython side by side }}} - -This created two plots one in each of the subplot area. The top -subplot holds a parabola and the bottom subplot holds a cosine -curve. - -As seen here we can use subplot command to switch between the subplot -as well, but we have to use the same arguments as we used to create -that subplot, otherwise the previous subplot at that place will be -automatically erased. It is clear from the two subplots that both have -different regular axes. For the cosine plot x-axis varies from 0 to -100 and y-axis varies from 0 to 1 where as for the parabolic plot the -x-axis varies from 0 to 10 and y-axis varies from 0 to 100 - -.. #[Nishanth]: stress on the similarity between subplot and figure - commands - -.. #[Madhu: I think they are not really similar. Trying to bring in - the similarity will confuse people I think.] - -%% 3 %% We know that the Pressure, Volume and Temperatures are held by -the equation PV = nRT where nR is a constant. Let us assume nR = .01 -Joules/Kelvin and T = 200K. V can be in the range from 21cc to -100cc. Draw two different plots as subplots, one being the Pressure -versus Volume plot and the other being Pressure versus Temparature -plot. - -{{{ Pause for a while and continue }}} - -To start with, we have been given the range of Volume using which we -can define the variable V:: - - V = linspace(21, 100, 500) - -Now we can create first subplot and draw Pressure versus Volume graph -using this V. We know that nRT is a constant which is equal to 2.0 -since nR = 0.01 Joules/Kelvin and T = 200 Kelvin:: - - subplot(2, 1, 1) - plot(V, 2.0/V) - -Now we can create the second subplot and draw the Pressure versus -Temparature plot as follows:: - - subplot(2, 1, 2) - plot(200, 2.0/V) - -Unfortunately we have an error now, telling x and y dimensions don't -match. This is because our V contains a set of values as returned by -linspace and hence 2.0/V which is the pressure also contains a set of -values. But the first argument to the plot command is a single -value. So to plot this data we need to create as many points as there -are in Pressure or Volume data for Temperature too, all having the -same value. This can be accomplished using:: - - T = linspace(200, 200, 500) - -We now have 500 values in T each with the value 200 Kelvin. Plotting -this data we get the required plot:: - - plot(T, 2.0/V) - -It is left as a homework to label both X and Y axes for each of the -two subplots. - -{{{ Show summary slide }}} - -.. #[Nishanth]: Exercises are missing in the script - one exercise for overlaid plot and legend - one for figure command - one for subplot must do - -This brings us to the end of another session. In this tutorial session -we learnt - - * How to draw multiple plots which are overlaid - * the figure command - * the legend command - * how to switch between the plots and perform some operations on each - of them like saving the plots and - * creating and switching between subplots - -.. #[Nishanth]: legend command can be told right after overlaid plots -.. #[Madhu: Incorporated] - -{{{ 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 88a01948450d -r d33698326409 multiple-plots/slides.org --- a/multiple-plots/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,123 +0,0 @@ -#+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: 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 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. -* 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 88a01948450d -r d33698326409 multiple-plots/slides.tex --- a/multiple-plots/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,106 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%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} -\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{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} -\date{} - -% DOCUMENT STARTS -\begin{document} - -\begin{frame} - \maketitle -\end{frame} - -\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} -\end{frame} - -\end{document} diff -r 88a01948450d -r d33698326409 multiple_plots/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple_plots/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,89 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Multiple plots appear in different figures by default. True or False? + + Answer: False + +#. What command is used to get individual plots separately? + + Answer: Figure + +#. Which figure is closed after the following commands are run? + +:: + + x = linspace(0, 50, 500) + figure(1) + plot(x, sin(x), 'b') + figure(2) + plot(x, cos(x), 'g') + xlabel('x') + ylabel('cos(x)') + close() + + Answer: Figure 2 + +#. Describe the plot obtained by the following commands:: + + x = linspace(0, 50, 500) + subplot(2, 1, 1) + plot(x, sin(x), 'b') + +Answer: A figure window with space for 2 plots one below the other is + obtained. The sine plot with blue line appears in the first row. + +#. Describe the plot obtained by the following commands:: + + x = linspace(0, 50, 500) + subplot(2, 1, 1) + plot(x, sin(x), 'b') + subplot(2, 1, 2) + plot(x, cos(x), 'g') + + Answer: 2 plots one below another. sine in blue on first row. cosine + in green in the second row. + +#. Describe the plot obtained by the following commands:: + + x = linspace(0, 50, 500) + subplot(2, 1, 1) + plot(x, sin(x), 'b') + subplot(2, 1, 2) + plot(x, cos(x), 'g') + subplot(2, 1, 1) + plot(x, tan(x), 'r') + + Answer: 2 plots one below another. tan in red on first row. cosine + in green in the second row. + + +#. Which of the following gives the correct legend for the commands below + + a. legend([sin, cos, tan]) + #. legend([tan, cos, sin]) + #. legend[(tan, cos, sin)] + #. legend(['sin', 'cos', 'tan']) + #. legend(['tan', 'cos', 'sin']) + +:: + + x = linspace(0, 50, 500) + figure(1) + plot(x, sin(x), 'b') + figure(2) + plot(x, cos(x), 'g') + figure(3) + plot(x, tan(x), 'b') + + Answer: legend(['tan', 'cos', 'sin']) + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Question 1 +2. Question 2 diff -r 88a01948450d -r d33698326409 multiple_plots/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple_plots/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,386 @@ +.. Objectives +.. ---------- + +.. * How to draw multiple plots which are overlaid +.. * the figure command +.. * the legend command +.. * how to switch between the plots and perform some operations on each +.. of them like saving the plots and +.. * creating and switching between subplots + + +.. Prerequisites +.. ------------- + +.. 1. using the plot command interactively +.. 2. embellishing a plot +.. 3. saving plots + +.. Author : Madhu + Internal Reviewer 1 : [potential reviewer: Puneeth] + Internal Reviewer 2 : Nishanth + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <, not OK> [] + + +Script +------ + +{{{ Show the slide containing the title }}} + +Hello friends. Welcome to this spoken tutorial on Multiple plots. + +{{{ Show the slide containing the outline }}} + +In this tutorial, we will learn how to draw more than one plot, how to +add legends to each plot to indicate what each plot represents. We +will also learn how to switch between the plots and create multiple +plots with different regular axes which are also called as subplots. + +.. #[Nishanth]: See diff - edited a grammatical mistake +.. #[Madhu: Done] + +{{{ Shift to terminal and start ipython -pylab }}} + +To begin with let us start ipython with pylab, by typing:: + + ipython -pylab + +on the terminal + +Let us first create set of points for our plot. For this we will use +the command called linspace:: + + x = linspace(0, 50, 10) + +linspace command creates 10 points in the interval between 0 and 50 +both inclusive. We assign these values to a variable called x. + +.. #[Nishanth]: pre requisite for this LO is basic plotting which + covers linspace and plot. So you may not need to + specify all that again. But not a problem if it is + there also. +.. #[Madhu: Since I thought the LOs are disconnected, I thought it is + better to give a very short intro to it] + +Now let us draw a plot simple sine plot using these points:: + + plot(x, sin(x)) + +This should give us a nice sine plot. + +{{{ Switch to the plot window }}} + +Oh! wait! Is that a nice sine plot? Does a sine plot actually look +like that? We know that a sine plot is a smooth curve. Is it not? What +really caused this? + +.. #[Nishanth]: See diff +.. #[Madhu: Done] + +{{{ pause for a while }}} + +A small investigation on linspace tells us that we chose too few +points in a large interval between 0 and 50 for the curve to be +smooth. This should also indicate that the plot command actually plots +the set of points given by x and sin(x) and it doesn't plot the +analytical function itself i.e. it plots the points given by +Analytical functions. So now let us use linspace again to get 500 +points between 0 and 100 and draw the sine plot + +.. #[Nishanth]: Here specify that when we do plot(x, sin(x) + it is actually plotting two sets of points + and not analytical functions. Hence the sharp + curve. +.. #[Madhu: Incorporated] + +{{{ Switch to ipython andtype }}} :: + + y = linspace(0, 50, 500) + plot(y, sin(y)) + +{{{ Change to the plot window }}} + +Now we see what we remember as a sine plot. A smooth curve. If we +carefully notice we also have two plots now one overlaid upon +another. In pylab, by default all the plots are overlaid. + +Since we have two plots now overlaid upon each other we would like to +have a way to indicate what each plot represents to distinguish +between them. This is accomplished using legends. Equivalently, the +legend command does this for us + +{{{ Switch to ipython }}}:: + + legend(['sin(x)', 'cos(x)']) + +.. #[Nishanth]: This legend may go up in the script. May be before + introducing the figure command itself. +.. #[Madhu: brought up] + +The legend command takes a single list of parameters where each +parameter is the text indicating the plots in the order of their +serial number. + +{{{ Switch to plot window }}} + +Now we can see the legends being displayed for the respective sine and +cosine plots on the plot area. + +We have learnt quite a lot of things now, so let us take up an +exercise problem. + +%% 1 %% Draw two plots overlaid upon each other, with the first plot + being a parabola of the form y = 4(x ^ 2) and the second being a + straight line of the form y = 2x + 3 in the interval -5 to 5. Use + colors to differentiate between the plots and use legends to + indicate what each plot is doing. + +{{{ pause for a while and continue from paused state }}} + +We can obtain the two plots in different colors using the following +commands:: + + x = linspace(-5, 5, 100) + plot(x, 4 * (x * x), 'b') + plot(x, (2 * x) + 3, 'g') + +Now we can use the legend command as:: + + legend(['Parabola', 'Straight Line']) + +Or we can also just give the equations of the plot:: + + legend(['y = 4(x ^ 2)', 'y = 2x + 3']) + +We now know how to draw multiple plots and use legends to indicate +which plot represents what function, but we would like to have more +control over the plots we draw. Like switch between them, perform some +operations or labelling on them individually and so on. Let us see how +to accomplish this. Before we move on, let us clear our screen. + +{{{ Switch to ipython }}}:: + + clf() + +To accomplishing more control over individual plots we use the figure +command:: + + x = linspace(0, 50, 500) + figure(1) + plot(x, sin(x), 'b') + figure(2) + plot(x, cos(x), 'g') + +{{{ Switch to plot window }}} + +Now we have two plots, a sine plot and a cosine plot in two different +figures. + +.. #[Nishanth]: figure(1) and figure(2) give two different plots. + The remaining script moves on the fact that they + give overlaid plots which is not the case. + So clear the figure and plot cos and sin without + introducing figure command. Then introduce legend + and finish off the everything on legend. + Then introduce figure command. + +.. #[Madhu: I have just moved up the text about legend command. I + think that should take care of what you suggested. If there is + some mistake with it, Punch please let me know in your next + review.] + +{{{ Have both plot window and ipython side by side }}} + +The figure command takes an integer as an argument which is the serial +number of the plot. This selects the corresponding plot. All the plot +commands we run after this are applied to the selected plot. In this +example figure 1 is the sine plot and figure 2 is the cosine plot. We +can, for example, save each plot separately + +{{{ Switch to ipython }}}:: + + savefig('/home/user/cosine.png') + figure(1) + title('sin(y)') + savefig('/home/user/sine.png') + +{{{ Have both plot window and ipython side by side }}} + +We also titled our first plot as 'sin(y)' which we did not do for +the second plot. + +Let us attempt another exercise problem + +%% 2 %% Draw a line of the form y = x as one figure and another line + of the form y = 2x + 3. Switch back to the first figure, annotate + the x and y intercepts. Now switch to the second figure and + annotate its x and y intercepts. Save each of them. + +{{{ Pause for a while and continue from the paused state }}} + +To solve this problem we should first create the first figure using +the figure command. Before that, let us first run clf command to make +sure all the previous plots are cleared:: + + clf() + figure(1) + x = linspace(-5, 5, 100) + plot(x, x) + +Now we can use figure command to create second plotting area and plot +the figure:: + + figure(2) + plot(x, ((2 * x) + 3)) + +Now to switch between the figures we can use figure command. So let us +switch to figure 1. We are asked to annotate x and y intercepts of the +figure 1 but since figure 1 passes through origin we will have to +annotate the origin. We will annotate the intercepts for the second +figure and save them as follows:: + + figure(1) + annotate('Origin', xy=(0.0, 0.0) + figure(2) + annotate('x-intercept', xy=(0, 3)) + annotate('y-intercept', xy=(0, -1.5)) + savefig('/home/fossee/plot2.png') + figure(1) + savefig('/home/fossee/plot1.png') + +At times we run into situations where we want to compare two plots and +in such cases we want to draw both the plots in the same plotting +area. The situation is such that the two plots have different regular +axes which means we cannot draw overlaid plots. In such cases we can +draw subplots. + +We use subplot command to accomplish this + +{{{ Switch to ipython }}}:: + + subplot(2, 1, 1) + +subplot command takes three arguments, the first being the number of +rows of subplots that must be created, + +{{{ Have both plot window and ipython side by side }}} + +in this case we have 2 as the first argument so it spilts the plotting area horizontally for +two subplots. The second argument specifies the number of coloumns of +subplots that must be created. We passed 1 as the argument so the +plotting area won't be split vertically and the last argument +specifies what subplot must be created now in the order of the serial +number. In this case we passed 1 as the argument, so the first subplot +that is top half is created. If we execute the subplot command as + +{{{ Switch to ipython }}}:: + + subplot(2, 1, 2) + +{{{ Switch to plot window }}} + +The lower subplot is created. Now we can draw plots in each of the +subplot area using the plot command. + +{{{ Switch to ipython }}}:: + + x = linspace(0, 50, 500) + plot(x, cos(x)) + subplot(2, 1, 1) + y = linspace(0, 5, 100) + plot(y, y ** 2) + +{{{ Have both plot window and ipython side by side }}} + +This created two plots one in each of the subplot area. The top +subplot holds a parabola and the bottom subplot holds a cosine +curve. + +As seen here we can use subplot command to switch between the subplot +as well, but we have to use the same arguments as we used to create +that subplot, otherwise the previous subplot at that place will be +automatically erased. It is clear from the two subplots that both have +different regular axes. For the cosine plot x-axis varies from 0 to +100 and y-axis varies from 0 to 1 where as for the parabolic plot the +x-axis varies from 0 to 10 and y-axis varies from 0 to 100 + +.. #[Nishanth]: stress on the similarity between subplot and figure + commands + +.. #[Madhu: I think they are not really similar. Trying to bring in + the similarity will confuse people I think.] + +%% 3 %% We know that the Pressure, Volume and Temperatures are held by +the equation PV = nRT where nR is a constant. Let us assume nR = .01 +Joules/Kelvin and T = 200K. V can be in the range from 21cc to +100cc. Draw two different plots as subplots, one being the Pressure +versus Volume plot and the other being Pressure versus Temparature +plot. + +{{{ Pause for a while and continue }}} + +To start with, we have been given the range of Volume using which we +can define the variable V:: + + V = linspace(21, 100, 500) + +Now we can create first subplot and draw Pressure versus Volume graph +using this V. We know that nRT is a constant which is equal to 2.0 +since nR = 0.01 Joules/Kelvin and T = 200 Kelvin:: + + subplot(2, 1, 1) + plot(V, 2.0/V) + +Now we can create the second subplot and draw the Pressure versus +Temparature plot as follows:: + + subplot(2, 1, 2) + plot(200, 2.0/V) + +Unfortunately we have an error now, telling x and y dimensions don't +match. This is because our V contains a set of values as returned by +linspace and hence 2.0/V which is the pressure also contains a set of +values. But the first argument to the plot command is a single +value. So to plot this data we need to create as many points as there +are in Pressure or Volume data for Temperature too, all having the +same value. This can be accomplished using:: + + T = linspace(200, 200, 500) + +We now have 500 values in T each with the value 200 Kelvin. Plotting +this data we get the required plot:: + + plot(T, 2.0/V) + +It is left as a homework to label both X and Y axes for each of the +two subplots. + +{{{ Show summary slide }}} + +.. #[Nishanth]: Exercises are missing in the script + one exercise for overlaid plot and legend + one for figure command + one for subplot must do + +This brings us to the end of another session. In this tutorial session +we learnt + + * How to draw multiple plots which are overlaid + * the figure command + * the legend command + * how to switch between the plots and perform some operations on each + of them like saving the plots and + * creating and switching between subplots + +.. #[Nishanth]: legend command can be told right after overlaid plots +.. #[Madhu: Incorporated] + +{{{ 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 88a01948450d -r d33698326409 multiple_plots/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple_plots/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,123 @@ +#+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: 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 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. +* 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 88a01948450d -r d33698326409 multiple_plots/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple_plots/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,106 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%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} +\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{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} +\date{} + +% DOCUMENT STARTS +\begin{document} + +\begin{frame} + \maketitle +\end{frame} + +\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} +\end{frame} + +\end{document} diff -r 88a01948450d -r d33698326409 other-type-of-plots/bar-chart-hatch.png Binary file other-type-of-plots/bar-chart-hatch.png has changed diff -r 88a01948450d -r d33698326409 other-type-of-plots/company-a-data.txt --- a/other-type-of-plots/company-a-data.txt Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,2 +0,0 @@ -2.000000000000000000e+03 2.001000000000000000e+03 2.002000000000000000e+03 2.003000000000000000e+03 2.004000000000000000e+03 2.005000000000000000e+03 2.006000000000000000e+03 2.007000000000000000e+03 2.008000000000000000e+03 2.009000000000000000e+03 2.010000000000000000e+03 -2.300000000000000000e+01 5.500000000000000000e+01 3.200000000000000000e+01 6.500000000000000000e+01 8.800000000000000000e+01 5.000000000000000000e+00 1.400000000000000000e+01 6.700000000000000000e+01 2.300000000000000000e+01 2.300000000000000000e+01 1.200000000000000000e+01 diff -r 88a01948450d -r d33698326409 other-type-of-plots/questions.rst --- a/other-type-of-plots/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,85 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. What is a log-log chart? - - a. A straight line graph - #. A graph on the logarithmic scale - #. A graph on the logarithmic scale with different scales for x and - y axes - #. A graph in which x axis is represented in logarithmic scale. - -Answer: A graph on the logarithmic scale with different scales for x - and y axes - -2. We have two lists with us ``years`` and ``profit``, what statement - can be issued to plot a pie chart to plot the profit for each year, - and each wedge has to be labelled with the corresponding year. - -Answer: pie(profit, labels=years) - -3. We have two lists with us ``years`` and profit``, what statement - can be issued to plot a scatter plot of the data in blue colored - diamonds. ``years`` has to be plotted along x-axis. - -Answer: scatter(year,profit,color='blue',marker='d') - -4. ``scatter(x, y, color='blue', marker='d')`` and ``plot(x, y, - color='b', marker='d')`` does exactly the same. - - a. True - #. False - -Answer: False - -5. ``plot(x, y, 'bd')`` creates a scattered plot in blue color and - diamond markers? - - a. True - #. False - -Answer: True - -6. ``scatter(x, y, 'bd')`` creates a scatter plot in blue color with - diamond markers. - - a. True - #. False - -Answer: False - -7. What statement can be issued to generate a bar chart with 135\ - :sup:`o` hatched bar filled with white. - - a. bar(x, y, color='w', hatch='/') - #. bar(x, y, color='w', hatch='\\') - #. bar(x, y, color='w', hatch='\') - #. bar(x, y, color='w', hatch='|') - -Answer: bar(x, y, color='w', hatch='\\') - -8. What statement can be issued to generate a bar chart with vertical - line hatching. - - a. bar(x, y, color='w', hatch='/') - #. bar(x, y, fill=False, hatch='\\') - #. bar(x, y, fill=False, hatch='|') - #. bar(x, y, color='w', hatch='\') - -Answer: bar(x, y, fill=False, hatch='|') - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Plot a log-log chart of the equation y=4*x\ :sup:`2` + 3*x for x - from -50 to 50. - -2. Plot a bar chart which is filled with white color and which is - hatched with 135\ :sup:`o` slanting lines for the data given in the - `file(company A data) `_ which has years and - profit percentage for each year. - diff -r 88a01948450d -r d33698326409 other-type-of-plots/quickref.tex --- a/other-type-of-plots/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,11 +0,0 @@ -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 88a01948450d -r d33698326409 other-type-of-plots/script.rst --- a/other-type-of-plots/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,264 +0,0 @@ -.. Objectives -.. ---------- - -.. At the end of this tutorial, you will be able to - -.. 1. Create scatter plot -.. #. Create pie charts -.. #. Create bar charts -.. #. Create log-log plots. - -.. Prerequisites -.. ------------- - -.. 1. should have ``ipython`` and ``pylab`` installed. -.. #. getting started with ``ipython``. -.. #. loading data from files -.. #. plotting the data - - -.. Author : Anoop Jacob Thomas - Internal Reviewer : Puneeth - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <10-11-2010, Anand, OK> [2010-10-05] - -.. #[Puneeth: Quickref missing] - -=================== -Other type of plots -=================== - -{{{ show the first slide }}} - -Hello and welcome to the tutorial ``The other kinds of plots``. - -.. #[Puneeth: this sentence doesn't read well] - -{{{ show the outline slide }}} - -.. #[Puneeth: motivate looking at other plots. Why are we looking at -.. them? Tell that we have only looked at one type of plot all the -.. while, etc.] - -Till now we have seen only one kind of plotting, and in this tutorial we -are going to see more kinds of plots such as the scatter plot, the pie chart, the bar chart and -the log-log plot. This tutorial covers the making of other kinds of -plots and also gives an introduction to matplotlib help. - -.. #[Puneeth: cover, see and introduce you. be consistent. does, the -.. "We" include the viewer or not?] - -Let us start with scatter plot. - -{{{ switch to the next slide, scatter plot }}} - -In a scatter plot, the data is displayed as a collection of points, -each having the value of one variable determining the position on the -horizontal axis and the value of the other variable determining the -position on the vertical axis. This kind of plot is also called a -scatter chart, a scatter diagram or a scatter graph. - -Before we proceed further, start your IPython interpreter -:: - - ipython -pylab - -{{{ open the ipython interpreter in the terminal using the command -ipython -pylab }}} - -{{{ switch to the next slide having the problem statement of first -exercise }}} - -Now, let us plot a scatter plot showing the percentage profit of -a company A from the year 2000-2010. The data for the same is available -in the file ``company-a-data.txt``. - -{{{ open the file company-a-data.txt and show the content }}} - -The data file has two lines with a set of values in each line, the -first line representing years and the second line representing the -profit percentages. - -{{{ close the file and switch to the terminal }}} - -To produce the scatter plot, we first need to load the data from the -file using ``loadtxt``. We learned it in one of the previous sessions, -and it can be done as :: - - year,profit = - loadtxt('/home/fossee/other-plot/company-a-data.txt',dtype=type(int())) - -By default loadtxt converts the value to float. The -``dtype=type(int())`` argument in loadtxt converts the value to -integer as we require the data as integer further in the tutorial. - -.. #[Puneeth: make a remark about dtype, that has not been covered in -.. the loadtxt tutorial.] - -{{{ switch to next slide, ``scatter`` function }}} - -Now in-order to generate the scatter graph we will use the function -``scatter()`` -:: - - scatter(year,profit) - -Notice that we passed two arguments to ``scatter()`` function, first -one the values in x-coordinate, year, and the other the values in -y-coordinate, the profit percentage. - -{{{ switch to the next slide which has the problem statement of -problem to be tried out }}} - -Now here is a question for you to try out, plot the same data with red -diamonds markers. - -.. **Clue** - *try scatter? in your ipython interpreter* - -Pause here and solve the question before moving on. - -.. scatter(year,profit,color='r',marker='d') - -Now let us see another kind of plot, the pie chart, for the same data. - -.. #[Puneeth: instead of just saying that, say that let's plot a pie -.. chart for the same data. continuity, will be good.] - -{{{ switch to the slide which says about pie chart }}} - -A pie chart or a circle graph is a circular chart divided into -sectors, illustrating proportion. - -{{{ switch to the slide showing the problem statement of second -exercise question }}} - -Plot a pie chart representing the profit percentage of company A, with -the same data from file ``company-a-data.txt``. So let us reuse the -data we have loaded from the file previously. - -.. #[Puneeth, this part can be move above.] - -{{{ switch to next slide, ``pie()`` function }}} - -We can plot the pie chart using the function ``pie()``. -:: - - pie(profit,labels=year) - -Notice that we passed two arguments to the function ``pie()``. First -one the values and the next one the set of labels to be used in the -pie chart. - -{{{ switch to the next slide which has the problem statement of -problem to be tried out }}} - -Now here is a question for you to try out, plot a pie chart with the -same data with colors for each wedges as white, red, black, magenta, -yellow, blue, green, cyan, yellow, magenta and blue respectively. - -.. **Clue** - *try pie? in your ipython interpreter* - -Pause here and solve the question before moving on. - -.. pie(t,labels=s,colors=('w','r','k','m','y','b','g','c','y','m','b')) - -{{{ switch to the slide which says about bar chart }}} - -Now let us move on to the bar charts. A bar chart or bar graph is a chart -with rectangular bars with lengths proportional to the values that -they represent. - -{{{ switch to the slide showing the problem statement of fifth -exercise question }}} - -Plot a bar chart representing the profit percentage of company A, with -the same data from file ``company-a-data.txt``. - -So let us reuse the data we have loaded from the file previously. - -{{{ switch to the next slide, ``bar()`` function }}} - -We can plot the bar chart using the function ``bar()``. -:: - - bar(year,profit) - -Note that the function ``bar()`` needs at least two arguments one the -values in x-coordinate and the other values in y-coordinate which is -used to determine the height of the bars. - -{{{ switch to the next slide which has the problem statement of -problem to be tried out }}} - -Now here is a question for you to try, plot a bar chart which is not -filled and which is hatched with 45\ :sup:`o` slanting lines as shown -in the image in the slide. The data for the chart may be obtained from -the file ``company-a-data.txt``. - -.. **Clue** - *try bar? in your ipython interpreter* - -.. bar(year,profit,fill=False,hatch='/') - -{{{ switch to the slide which says about log-log graph }}} - -Now let us move on to the log-log plot. A log-log graph or a log-log plot is -a two-dimensional graph of numerical data that uses logarithmic scales -on both the horizontal and vertical axes. Because of the nonlinear -scaling of the axes, a function of the form y = ax\ :sup:`b` will -appear as a straight line on a log-log graph - -{{{ switch to the slide showing the problem statement of fourth -exercise question }}} - - -Plot a `log-log` chart of y=5*x\ :sup:`3` for x from 1-20. - -Before we actually plot let us calculate the points needed for -that. -:: - - x = linspace(1,20,100) - y = 5*x**3 - -{{{ switch to next slide, ``loglog()`` function }}} - -Now we can plot the log-log chart using ``loglog()`` function, -:: - - loglog(x,y) - -To understand the difference between a normal ``plot`` and a ``log-log -plot`` let us create another plot using the function ``plot``. -:: - - figure(2) - plot(x,y) - -{{{ show both the plots side by side }}} - -So that was ``log-log() plot``. - -{{{ switch to the next slide which says: "How to get help on -matplotlib online"}}} - -Now we will see few more plots and also see how to access help of -matplotlib over the internet. - -Help about matplotlib can be obtained from -matplotlib.sourceforge.net/contents.html - - -More plots can be seen at -matplotlib.sourceforge.net/users/screenshots.html and also at -matplotlib.sourceforge.net/gallery.html - -{{{ switch to summary slide }}} - -Now we have come to the end of this tutorial. We have covered scatter -plot, pie chart, bar chart, log-log plot and also saw few other plots -and covered how to access the matplotlib online help. - -{{{ switch to the thank you slide }}} - -Thank you! diff -r 88a01948450d -r d33698326409 other-type-of-plots/slides.org --- a/other-type-of-plots/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,137 +0,0 @@ -#+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: Other type of plots -#+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 - - Scatter plot - - Pie chart - - Bar chart - - Log-log Plot - - ~matplotlib~ help -* Exercise 1: Scatter plot - Plot a scatter plot showing the percentage profit of Company A from the year 2000 - to 2010. The data for the same is available in the file ~company-a-data.txt~. -* ~scatter()~ function - - /Syntax :/ scatter(x,y) - - x, a sequence of data - - y, a sequence of data, the same length of x - : In []: scatter(year, profit) -* Exercise 2: Scatter plot - Plot a scatter plot of the same data in ~company-a-data.txt~ with red diamond markers. - : - *Clue* - /try scatter? in your ipython interpreter/ -* Pie chart - Pie chart - a circle graph divided into sectors, illustrating proportion. -* Exercise 3: Pie chart - Plot a pie chart representing the profit percentage of company A, with the data - from the file ~company-a-data.txt~. - : - /(we can reuse the data in lists year and profit)/ -* ~pie()~ function - - /Syntax :/ pie(values, labels=labels) - - values, the data to be plotted - - labels, the label for each wedge in the pie chart - : In []: pie(profit, labels=year) -* Exercise 4: Pie chart - Plot a pie chart with the same data with colors for each wedges as white, red, - magenta, yellow, blue, green, cyan, yellow, magenta, and blue. - : - *Clue* - /try pie? in your ipython interpreter/ -* Bar chart - Bar chart - a chart with rectangular bars with lengths proportional - to the values that they represent. -* Exercise 5: Bar chart - Plot a bar chart representing the profit percentage of company A, with the data - from the file ~company-a-data.txt~. - : - /(we can reuse the data in lists year and profit)/ -* ~bar()~ function - - /Syntax :/ bar(x, y) - - x, a sequence of data - - y, a sequence of data, the same length of x - : In []: bar(year, profit) -* Exercise 6: Bar chart - Plot a bar chart which is not filled and which is hatched with - #+begin_latex - $45^o$ - #+end_latex - slanting lines as shown in the image. The data for the chart may be - obtained from the file ~company-a-data.txt~. - #+begin_latex - \begin{center} - \includegraphics[scale=0.3]{bar-chart-hatch} - \end{center} - #+end_latex - *Clue* - /try bar? in your ipython interpreter/ -* Log-log graph - - Log-log graph - - 2-dimensional graph. - - uses logarithmic scales on both axes. - - graph appears as straight line due to non-linear scaling. -* Exercise 7: - Plot a log-log chart of - #+begin_latex - $y = 5x^3$ - #+end_latex - for x from 1-20. -* ~loglog()~ function - - /Syntax :/ loglog(x, y) - - x, a sequence of data - - y, a sequence of data, the same length of x - : In []: loglog(x, y) -* Getting help on ~matplotlib~ - - Help - - [[matplotlib.sourceforge.net/contents.html]] - - More plots - - [[matplotlib.sourceforge.net/users/screenshots.html]] - - [[matplotlib.sourceforge.net/gallery.html]] - -* Summary - - Scatter plot (~scatter()~) - - Pie chart (~pie()~) - - Bar chart (~bar()~) - - Log-log plot (~loglog()~) - - ~matplotlib~ online help -* 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 88a01948450d -r d33698326409 other-type-of-plots/slides.tex --- a/other-type-of-plots/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,280 +0,0 @@ -% Created 2010-10-12 Tue 16:22 -\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{Other type of plots} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Scatter plot -\item Pie chart -\item Bar chart -\item Log-log Plot -\item \texttt{matplotlib} help -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Exercise 1: Scatter plot} -\label{sec-2} - - Plot a scatter plot showing the percentage profit of Company A from the year 2000 - to 2010. The data for the same is available in the file \texttt{company-a-data.txt}. -\end{frame} -\begin{frame}[fragile] -\frametitle{\texttt{scatter()} function} -\label{sec-3} - -\begin{itemize} -\item \emph{Syntax :} scatter(x,y) - -\begin{itemize} -\item x, a sequence of data -\item y, a sequence of data, the same length of x -\end{itemize} - -\end{itemize} - -\begin{verbatim} - In []: scatter(year, profit) -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Exercise 2: Scatter plot} -\label{sec-4} - - Plot a scatter plot of the same data in \texttt{company-a-data.txt} with red diamond markers. -\begin{verbatim} - -\end{verbatim} - - \textbf{Clue} - \emph{try scatter? in your ipython interpreter} -\end{frame} -\begin{frame} -\frametitle{Pie chart} -\label{sec-5} - - Pie chart - a circle graph divided into sectors, illustrating proportion. -\end{frame} -\begin{frame}[fragile] -\frametitle{Exercise 3: Pie chart} -\label{sec-6} - - Plot a pie chart representing the profit percentage of company A, with the data - from the file \texttt{company-a-data.txt}. -\begin{verbatim} - -\end{verbatim} - - \emph{(we can reuse the data in lists year and profit)} -\end{frame} -\begin{frame}[fragile] -\frametitle{\texttt{pie()} function} -\label{sec-7} - -\begin{itemize} -\item \emph{Syntax :} pie(values, labels=labels) - -\begin{itemize} -\item values, the data to be plotted -\item labels, the label for each wedge in the pie chart -\end{itemize} - -\end{itemize} - -\begin{verbatim} - In []: pie(profit, labels=year) -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Exercise 4: Pie chart} -\label{sec-8} - - Plot a pie chart with the same data with colors for each wedges as white, red, - magenta, yellow, blue, green, cyan, yellow, magenta, and blue. -\begin{verbatim} - -\end{verbatim} - - \textbf{Clue} - \emph{try pie? in your ipython interpreter} -\end{frame} -\begin{frame} -\frametitle{Bar chart} -\label{sec-9} - - Bar chart - a chart with rectangular bars with lengths proportional - to the values that they represent. -\end{frame} -\begin{frame}[fragile] -\frametitle{Exercise 5: Bar chart} -\label{sec-10} - - Plot a bar chart representing the profit percentage of company A, with the data - from the file \texttt{company-a-data.txt}. -\begin{verbatim} - -\end{verbatim} - - \emph{(we can reuse the data in lists year and profit)} -\end{frame} -\begin{frame}[fragile] -\frametitle{\texttt{bar()} function} -\label{sec-11} - -\begin{itemize} -\item \emph{Syntax :} bar(x, y) - -\begin{itemize} -\item x, a sequence of data -\item y, a sequence of data, the same length of x -\end{itemize} - -\end{itemize} - -\begin{verbatim} - In []: bar(year, profit) -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Exercise 6: Bar chart} -\label{sec-12} - - Plot a bar chart which is not filled and which is hatched with - $45^o$ - slanting lines as shown in the image. The data for the chart may be - obtained from the file \texttt{company-a-data.txt}. - \begin{center} - \includegraphics[scale=0.3]{bar-chart-hatch} - \end{center} - \textbf{Clue} - \emph{try bar? in your ipython interpreter} -\end{frame} -\begin{frame} -\frametitle{Log-log graph} -\label{sec-13} - -\begin{itemize} -\item Log-log graph - -\begin{itemize} -\item 2-dimensional graph. -\item uses logarithmic scales on both axes. -\item graph appears as straight line due to non-linear scaling. -\end{itemize} - -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Exercise 7:} -\label{sec-14} - - Plot a log-log chart of - $y = 5x^3$ - for x from 1-20. -\end{frame} -\begin{frame}[fragile] -\frametitle{\texttt{loglog()} function} -\label{sec-15} - -\begin{itemize} -\item \emph{Syntax :} loglog(x, y) - -\begin{itemize} -\item x, a sequence of data -\item y, a sequence of data, the same length of x -\end{itemize} - -\end{itemize} - -\begin{verbatim} - In []: loglog(x, y) -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Getting help on \texttt{matplotlib}} -\label{sec-16} - -\begin{itemize} -\item Help - -\begin{itemize} -\item \hyperref[sec-16]{matplotlib.sourceforge.net/contents.html} -\end{itemize} - -\item More plots - -\begin{itemize} -\item \hyperref[sec-16]{matplotlib.sourceforge.net/users/screenshots.html} -\item \hyperref[sec-16]{matplotlib.sourceforge.net/gallery.html} -\end{itemize} - -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-17} - -\begin{itemize} -\item Scatter plot (\texttt{scatter()}) -\item Pie chart (\texttt{pie()}) -\item Bar chart (\texttt{bar()}) -\item Log-log plot (\texttt{loglog()}) -\item \texttt{matplotlib} online help -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-18} - - \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 88a01948450d -r d33698326409 other_type_of_plots/bar-chart-hatch.png Binary file other_type_of_plots/bar-chart-hatch.png has changed diff -r 88a01948450d -r d33698326409 other_type_of_plots/company-a-data.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other_type_of_plots/company-a-data.txt Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,2 @@ +2.000000000000000000e+03 2.001000000000000000e+03 2.002000000000000000e+03 2.003000000000000000e+03 2.004000000000000000e+03 2.005000000000000000e+03 2.006000000000000000e+03 2.007000000000000000e+03 2.008000000000000000e+03 2.009000000000000000e+03 2.010000000000000000e+03 +2.300000000000000000e+01 5.500000000000000000e+01 3.200000000000000000e+01 6.500000000000000000e+01 8.800000000000000000e+01 5.000000000000000000e+00 1.400000000000000000e+01 6.700000000000000000e+01 2.300000000000000000e+01 2.300000000000000000e+01 1.200000000000000000e+01 diff -r 88a01948450d -r d33698326409 other_type_of_plots/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other_type_of_plots/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,85 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. What is a log-log chart? + + a. A straight line graph + #. A graph on the logarithmic scale + #. A graph on the logarithmic scale with different scales for x and + y axes + #. A graph in which x axis is represented in logarithmic scale. + +Answer: A graph on the logarithmic scale with different scales for x + and y axes + +2. We have two lists with us ``years`` and ``profit``, what statement + can be issued to plot a pie chart to plot the profit for each year, + and each wedge has to be labelled with the corresponding year. + +Answer: pie(profit, labels=years) + +3. We have two lists with us ``years`` and profit``, what statement + can be issued to plot a scatter plot of the data in blue colored + diamonds. ``years`` has to be plotted along x-axis. + +Answer: scatter(year,profit,color='blue',marker='d') + +4. ``scatter(x, y, color='blue', marker='d')`` and ``plot(x, y, + color='b', marker='d')`` does exactly the same. + + a. True + #. False + +Answer: False + +5. ``plot(x, y, 'bd')`` creates a scattered plot in blue color and + diamond markers? + + a. True + #. False + +Answer: True + +6. ``scatter(x, y, 'bd')`` creates a scatter plot in blue color with + diamond markers. + + a. True + #. False + +Answer: False + +7. What statement can be issued to generate a bar chart with 135\ + :sup:`o` hatched bar filled with white. + + a. bar(x, y, color='w', hatch='/') + #. bar(x, y, color='w', hatch='\\') + #. bar(x, y, color='w', hatch='\') + #. bar(x, y, color='w', hatch='|') + +Answer: bar(x, y, color='w', hatch='\\') + +8. What statement can be issued to generate a bar chart with vertical + line hatching. + + a. bar(x, y, color='w', hatch='/') + #. bar(x, y, fill=False, hatch='\\') + #. bar(x, y, fill=False, hatch='|') + #. bar(x, y, color='w', hatch='\') + +Answer: bar(x, y, fill=False, hatch='|') + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Plot a log-log chart of the equation y=4*x\ :sup:`2` + 3*x for x + from -50 to 50. + +2. Plot a bar chart which is filled with white color and which is + hatched with 135\ :sup:`o` slanting lines for the data given in the + `file(company A data) `_ which has years and + profit percentage for each year. + diff -r 88a01948450d -r d33698326409 other_type_of_plots/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other_type_of_plots/quickref.tex Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 other_type_of_plots/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other_type_of_plots/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,264 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Create scatter plot +.. #. Create pie charts +.. #. Create bar charts +.. #. Create log-log plots. + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` and ``pylab`` installed. +.. #. getting started with ``ipython``. +.. #. loading data from files +.. #. plotting the data + + +.. Author : Anoop Jacob Thomas + Internal Reviewer : Puneeth + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <10-11-2010, Anand, OK> [2010-10-05] + +.. #[Puneeth: Quickref missing] + +=================== +Other type of plots +=================== + +{{{ show the first slide }}} + +Hello and welcome to the tutorial ``The other kinds of plots``. + +.. #[Puneeth: this sentence doesn't read well] + +{{{ show the outline slide }}} + +.. #[Puneeth: motivate looking at other plots. Why are we looking at +.. them? Tell that we have only looked at one type of plot all the +.. while, etc.] + +Till now we have seen only one kind of plotting, and in this tutorial we +are going to see more kinds of plots such as the scatter plot, the pie chart, the bar chart and +the log-log plot. This tutorial covers the making of other kinds of +plots and also gives an introduction to matplotlib help. + +.. #[Puneeth: cover, see and introduce you. be consistent. does, the +.. "We" include the viewer or not?] + +Let us start with scatter plot. + +{{{ switch to the next slide, scatter plot }}} + +In a scatter plot, the data is displayed as a collection of points, +each having the value of one variable determining the position on the +horizontal axis and the value of the other variable determining the +position on the vertical axis. This kind of plot is also called a +scatter chart, a scatter diagram or a scatter graph. + +Before we proceed further, start your IPython interpreter +:: + + ipython -pylab + +{{{ open the ipython interpreter in the terminal using the command +ipython -pylab }}} + +{{{ switch to the next slide having the problem statement of first +exercise }}} + +Now, let us plot a scatter plot showing the percentage profit of +a company A from the year 2000-2010. The data for the same is available +in the file ``company-a-data.txt``. + +{{{ open the file company-a-data.txt and show the content }}} + +The data file has two lines with a set of values in each line, the +first line representing years and the second line representing the +profit percentages. + +{{{ close the file and switch to the terminal }}} + +To produce the scatter plot, we first need to load the data from the +file using ``loadtxt``. We learned it in one of the previous sessions, +and it can be done as :: + + year,profit = + loadtxt('/home/fossee/other-plot/company-a-data.txt',dtype=type(int())) + +By default loadtxt converts the value to float. The +``dtype=type(int())`` argument in loadtxt converts the value to +integer as we require the data as integer further in the tutorial. + +.. #[Puneeth: make a remark about dtype, that has not been covered in +.. the loadtxt tutorial.] + +{{{ switch to next slide, ``scatter`` function }}} + +Now in-order to generate the scatter graph we will use the function +``scatter()`` +:: + + scatter(year,profit) + +Notice that we passed two arguments to ``scatter()`` function, first +one the values in x-coordinate, year, and the other the values in +y-coordinate, the profit percentage. + +{{{ switch to the next slide which has the problem statement of +problem to be tried out }}} + +Now here is a question for you to try out, plot the same data with red +diamonds markers. + +.. **Clue** - *try scatter? in your ipython interpreter* + +Pause here and solve the question before moving on. + +.. scatter(year,profit,color='r',marker='d') + +Now let us see another kind of plot, the pie chart, for the same data. + +.. #[Puneeth: instead of just saying that, say that let's plot a pie +.. chart for the same data. continuity, will be good.] + +{{{ switch to the slide which says about pie chart }}} + +A pie chart or a circle graph is a circular chart divided into +sectors, illustrating proportion. + +{{{ switch to the slide showing the problem statement of second +exercise question }}} + +Plot a pie chart representing the profit percentage of company A, with +the same data from file ``company-a-data.txt``. So let us reuse the +data we have loaded from the file previously. + +.. #[Puneeth, this part can be move above.] + +{{{ switch to next slide, ``pie()`` function }}} + +We can plot the pie chart using the function ``pie()``. +:: + + pie(profit,labels=year) + +Notice that we passed two arguments to the function ``pie()``. First +one the values and the next one the set of labels to be used in the +pie chart. + +{{{ switch to the next slide which has the problem statement of +problem to be tried out }}} + +Now here is a question for you to try out, plot a pie chart with the +same data with colors for each wedges as white, red, black, magenta, +yellow, blue, green, cyan, yellow, magenta and blue respectively. + +.. **Clue** - *try pie? in your ipython interpreter* + +Pause here and solve the question before moving on. + +.. pie(t,labels=s,colors=('w','r','k','m','y','b','g','c','y','m','b')) + +{{{ switch to the slide which says about bar chart }}} + +Now let us move on to the bar charts. A bar chart or bar graph is a chart +with rectangular bars with lengths proportional to the values that +they represent. + +{{{ switch to the slide showing the problem statement of fifth +exercise question }}} + +Plot a bar chart representing the profit percentage of company A, with +the same data from file ``company-a-data.txt``. + +So let us reuse the data we have loaded from the file previously. + +{{{ switch to the next slide, ``bar()`` function }}} + +We can plot the bar chart using the function ``bar()``. +:: + + bar(year,profit) + +Note that the function ``bar()`` needs at least two arguments one the +values in x-coordinate and the other values in y-coordinate which is +used to determine the height of the bars. + +{{{ switch to the next slide which has the problem statement of +problem to be tried out }}} + +Now here is a question for you to try, plot a bar chart which is not +filled and which is hatched with 45\ :sup:`o` slanting lines as shown +in the image in the slide. The data for the chart may be obtained from +the file ``company-a-data.txt``. + +.. **Clue** - *try bar? in your ipython interpreter* + +.. bar(year,profit,fill=False,hatch='/') + +{{{ switch to the slide which says about log-log graph }}} + +Now let us move on to the log-log plot. A log-log graph or a log-log plot is +a two-dimensional graph of numerical data that uses logarithmic scales +on both the horizontal and vertical axes. Because of the nonlinear +scaling of the axes, a function of the form y = ax\ :sup:`b` will +appear as a straight line on a log-log graph + +{{{ switch to the slide showing the problem statement of fourth +exercise question }}} + + +Plot a `log-log` chart of y=5*x\ :sup:`3` for x from 1-20. + +Before we actually plot let us calculate the points needed for +that. +:: + + x = linspace(1,20,100) + y = 5*x**3 + +{{{ switch to next slide, ``loglog()`` function }}} + +Now we can plot the log-log chart using ``loglog()`` function, +:: + + loglog(x,y) + +To understand the difference between a normal ``plot`` and a ``log-log +plot`` let us create another plot using the function ``plot``. +:: + + figure(2) + plot(x,y) + +{{{ show both the plots side by side }}} + +So that was ``log-log() plot``. + +{{{ switch to the next slide which says: "How to get help on +matplotlib online"}}} + +Now we will see few more plots and also see how to access help of +matplotlib over the internet. + +Help about matplotlib can be obtained from +matplotlib.sourceforge.net/contents.html + + +More plots can be seen at +matplotlib.sourceforge.net/users/screenshots.html and also at +matplotlib.sourceforge.net/gallery.html + +{{{ switch to summary slide }}} + +Now we have come to the end of this tutorial. We have covered scatter +plot, pie chart, bar chart, log-log plot and also saw few other plots +and covered how to access the matplotlib online help. + +{{{ switch to the thank you slide }}} + +Thank you! diff -r 88a01948450d -r d33698326409 other_type_of_plots/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other_type_of_plots/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,137 @@ +#+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: Other type of plots +#+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 + - Scatter plot + - Pie chart + - Bar chart + - Log-log Plot + - ~matplotlib~ help +* Exercise 1: Scatter plot + Plot a scatter plot showing the percentage profit of Company A from the year 2000 + to 2010. The data for the same is available in the file ~company-a-data.txt~. +* ~scatter()~ function + - /Syntax :/ scatter(x,y) + - x, a sequence of data + - y, a sequence of data, the same length of x + : In []: scatter(year, profit) +* Exercise 2: Scatter plot + Plot a scatter plot of the same data in ~company-a-data.txt~ with red diamond markers. + : + *Clue* - /try scatter? in your ipython interpreter/ +* Pie chart + Pie chart - a circle graph divided into sectors, illustrating proportion. +* Exercise 3: Pie chart + Plot a pie chart representing the profit percentage of company A, with the data + from the file ~company-a-data.txt~. + : + /(we can reuse the data in lists year and profit)/ +* ~pie()~ function + - /Syntax :/ pie(values, labels=labels) + - values, the data to be plotted + - labels, the label for each wedge in the pie chart + : In []: pie(profit, labels=year) +* Exercise 4: Pie chart + Plot a pie chart with the same data with colors for each wedges as white, red, + magenta, yellow, blue, green, cyan, yellow, magenta, and blue. + : + *Clue* - /try pie? in your ipython interpreter/ +* Bar chart + Bar chart - a chart with rectangular bars with lengths proportional + to the values that they represent. +* Exercise 5: Bar chart + Plot a bar chart representing the profit percentage of company A, with the data + from the file ~company-a-data.txt~. + : + /(we can reuse the data in lists year and profit)/ +* ~bar()~ function + - /Syntax :/ bar(x, y) + - x, a sequence of data + - y, a sequence of data, the same length of x + : In []: bar(year, profit) +* Exercise 6: Bar chart + Plot a bar chart which is not filled and which is hatched with + #+begin_latex + $45^o$ + #+end_latex + slanting lines as shown in the image. The data for the chart may be + obtained from the file ~company-a-data.txt~. + #+begin_latex + \begin{center} + \includegraphics[scale=0.3]{bar-chart-hatch} + \end{center} + #+end_latex + *Clue* - /try bar? in your ipython interpreter/ +* Log-log graph + - Log-log graph + - 2-dimensional graph. + - uses logarithmic scales on both axes. + - graph appears as straight line due to non-linear scaling. +* Exercise 7: + Plot a log-log chart of + #+begin_latex + $y = 5x^3$ + #+end_latex + for x from 1-20. +* ~loglog()~ function + - /Syntax :/ loglog(x, y) + - x, a sequence of data + - y, a sequence of data, the same length of x + : In []: loglog(x, y) +* Getting help on ~matplotlib~ + - Help + - [[matplotlib.sourceforge.net/contents.html]] + - More plots + - [[matplotlib.sourceforge.net/users/screenshots.html]] + - [[matplotlib.sourceforge.net/gallery.html]] + +* Summary + - Scatter plot (~scatter()~) + - Pie chart (~pie()~) + - Bar chart (~bar()~) + - Log-log plot (~loglog()~) + - ~matplotlib~ online help +* 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 88a01948450d -r d33698326409 other_type_of_plots/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other_type_of_plots/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,280 @@ +% Created 2010-10-12 Tue 16:22 +\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{Other type of plots} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Scatter plot +\item Pie chart +\item Bar chart +\item Log-log Plot +\item \texttt{matplotlib} help +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 1: Scatter plot} +\label{sec-2} + + Plot a scatter plot showing the percentage profit of Company A from the year 2000 + to 2010. The data for the same is available in the file \texttt{company-a-data.txt}. +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{scatter()} function} +\label{sec-3} + +\begin{itemize} +\item \emph{Syntax :} scatter(x,y) + +\begin{itemize} +\item x, a sequence of data +\item y, a sequence of data, the same length of x +\end{itemize} + +\end{itemize} + +\begin{verbatim} + In []: scatter(year, profit) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 2: Scatter plot} +\label{sec-4} + + Plot a scatter plot of the same data in \texttt{company-a-data.txt} with red diamond markers. +\begin{verbatim} + +\end{verbatim} + + \textbf{Clue} - \emph{try scatter? in your ipython interpreter} +\end{frame} +\begin{frame} +\frametitle{Pie chart} +\label{sec-5} + + Pie chart - a circle graph divided into sectors, illustrating proportion. +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 3: Pie chart} +\label{sec-6} + + Plot a pie chart representing the profit percentage of company A, with the data + from the file \texttt{company-a-data.txt}. +\begin{verbatim} + +\end{verbatim} + + \emph{(we can reuse the data in lists year and profit)} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{pie()} function} +\label{sec-7} + +\begin{itemize} +\item \emph{Syntax :} pie(values, labels=labels) + +\begin{itemize} +\item values, the data to be plotted +\item labels, the label for each wedge in the pie chart +\end{itemize} + +\end{itemize} + +\begin{verbatim} + In []: pie(profit, labels=year) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 4: Pie chart} +\label{sec-8} + + Plot a pie chart with the same data with colors for each wedges as white, red, + magenta, yellow, blue, green, cyan, yellow, magenta, and blue. +\begin{verbatim} + +\end{verbatim} + + \textbf{Clue} - \emph{try pie? in your ipython interpreter} +\end{frame} +\begin{frame} +\frametitle{Bar chart} +\label{sec-9} + + Bar chart - a chart with rectangular bars with lengths proportional + to the values that they represent. +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 5: Bar chart} +\label{sec-10} + + Plot a bar chart representing the profit percentage of company A, with the data + from the file \texttt{company-a-data.txt}. +\begin{verbatim} + +\end{verbatim} + + \emph{(we can reuse the data in lists year and profit)} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{bar()} function} +\label{sec-11} + +\begin{itemize} +\item \emph{Syntax :} bar(x, y) + +\begin{itemize} +\item x, a sequence of data +\item y, a sequence of data, the same length of x +\end{itemize} + +\end{itemize} + +\begin{verbatim} + In []: bar(year, profit) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Exercise 6: Bar chart} +\label{sec-12} + + Plot a bar chart which is not filled and which is hatched with + $45^o$ + slanting lines as shown in the image. The data for the chart may be + obtained from the file \texttt{company-a-data.txt}. + \begin{center} + \includegraphics[scale=0.3]{bar-chart-hatch} + \end{center} + \textbf{Clue} - \emph{try bar? in your ipython interpreter} +\end{frame} +\begin{frame} +\frametitle{Log-log graph} +\label{sec-13} + +\begin{itemize} +\item Log-log graph + +\begin{itemize} +\item 2-dimensional graph. +\item uses logarithmic scales on both axes. +\item graph appears as straight line due to non-linear scaling. +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 7:} +\label{sec-14} + + Plot a log-log chart of + $y = 5x^3$ + for x from 1-20. +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{loglog()} function} +\label{sec-15} + +\begin{itemize} +\item \emph{Syntax :} loglog(x, y) + +\begin{itemize} +\item x, a sequence of data +\item y, a sequence of data, the same length of x +\end{itemize} + +\end{itemize} + +\begin{verbatim} + In []: loglog(x, y) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Getting help on \texttt{matplotlib}} +\label{sec-16} + +\begin{itemize} +\item Help + +\begin{itemize} +\item \hyperref[sec-16]{matplotlib.sourceforge.net/contents.html} +\end{itemize} + +\item More plots + +\begin{itemize} +\item \hyperref[sec-16]{matplotlib.sourceforge.net/users/screenshots.html} +\item \hyperref[sec-16]{matplotlib.sourceforge.net/gallery.html} +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-17} + +\begin{itemize} +\item Scatter plot (\texttt{scatter()}) +\item Pie chart (\texttt{pie()}) +\item Bar chart (\texttt{bar()}) +\item Log-log plot (\texttt{loglog()}) +\item \texttt{matplotlib} online help +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-18} + + \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 88a01948450d -r d33698326409 plotting-data.rst --- a/plotting-data.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,137 +0,0 @@ -Plotting Experimental Data -============================= -Hello and welcome , this tutorial on Plotting Experimental data is -presented by the fossee team. - -{{{ Show the slide containing title }}} - - -{{{ Show the Outline Slide }}} - -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 -sequence. - -3. We will also see how we can use our graph to indicate Error. - -One needs to be fimiliar with the concepts of plotting -mathematical functions in Python. - -We will use data from a Simple Pendulum Experiment to illustrate our -points. - -{{{ Simple Pendulum data Slide }}} - - - - -As we know for a simple pendulum length,L is directly proportional to -the square of time,T. We shall be plotting L and T^2 values. - - -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 - -L,t type in ipython shell. :: - - 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] - - - -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) - - array([ 0.4761, 0.81 , 1.4161, 1.69 , 2.1609, 2.4964, 3.1329, - 3.3489, 3.7636]) - - -Now to plot L vs T^2 we will simply type :: - - In []: plot(L,t,.) - -'.' here represents to plot use small dots for the point. :: - - In []: clf() - -You can also specify 'o' for big dots.:: - - In []: plot(L,t,o) - - In []: clf() - - -{{{ Slide with Error data included }}} - - -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 :: - - 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] - - - -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.') - -This gives a plot with error bar for x and y axis. The dots are of -blue color. - - -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') - - - -thats it. you can explore other options to errorbar using the documentation -of errorbar.:: - - In []: errorbar? - - -{{{ Summary Slides }}} - -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. - -3. 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. - - - {{{ Show the "sponsored by FOSSEE" slide }}} - - - -This tutorial was created as a part of FOSSEE project. - -Hope you have enjoyed and found it useful. - - Thankyou - - - -Author : Amit Sethi -Internal Reviewer : -Internal Reviewer 2 : diff -r 88a01948450d -r d33698326409 plotting-data/questions.rst --- a/plotting-data/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,73 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. How do you declare a sequence of numbers in python? - Give example . - - Comma seperated numbers inside two square brackets. - - seq=[1.5,3.2,8.7] - - -2. Square the following sequence? - - distance_values=[2.1,4.6,8.72,9.03]. - - square(distance_values) - - - -3. How do you plot the data as points using plot function? - - By passing an extra parameter '.'. - -.. #[[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. - -6. How do I get large red colour dots on a plot? - - By passing the paramter 'ro'. - -7. What are the parameters 'xerr' and 'yerr' in errorbar function for? - - xerr - List of error values of variable on x axis. - yerr - List of error values of variable on y ayis. - -8. How would you plot error bar with a line? - - The fmt parameter for a line will be '-'. - - - - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Plot an errorbar for following experimental data. - - | X | Y | Xerr | Yerr | - | 154.9 | 8106 | 8.51 | 165.8 | - | 154.3 | 8138 | 8.50 | 166.3 | - | 148.7 | 8148 | 7.78 | 161.2 | - | 149.6 | 8171 | 7.81 | 162.6 | - -in red colour with large dots - -2. List the parameters for errorbar and their function? diff -r 88a01948450d -r d33698326409 plotting-data/quickref.tex --- a/plotting-data/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,15 +0,0 @@ -Creating a Sequence:\\ -{\ex \lstinline| L = [0.1, 0.2, 0.3] |} - -Squaring a sequence:\\ -{\ex \lstinline| tsquare=square(t) |} - -Plotting two list using small dots:\\ -{\ex \lstinline| plot(L,tsquare,'.') |} - -Plotting two list using big dots:\\ -{\ex \lstinline| plot(L,tsquare,'o') |} - -Plotting an errorbar in blue color:\\ -{\ex \lstinline| errorbar(L,tsquare,xerr=delta_L, yerr=delta_T, fmt='b.') |} - diff -r 88a01948450d -r d33698326409 plotting-data/script.rst --- a/plotting-data/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,218 +0,0 @@ -.. Objectives -.. ---------- - -.. By the end of this tutorial, you will be able to - -.. 1. Defining a list of numbers -.. 2. Squaring a list of numbers -.. 3. Plotting data points. -.. 4. Plotting errorbars. - - -.. Prerequisites -.. ------------- - -.. 1. getting started with plotting - - -.. Author : Amit - 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 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 familiar with elementwise squaring of such a -sequence. - -3. How to plot data points using python. - -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. - -.. #[[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 -the square of time,T. We shall be plotting L and T^2 values. - - -First we will have to initiate L and T values. We initiate them as sequence -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. - -.. #[[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]] - -{{{ 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 -with argument t.This is saved into the variable tsquare.:: - - 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 :: - - plot(L,tsquare,'.') - -.. #[[Anoop: be consistent with the spacing and all.]] - -'.' here represents to plot use small dots for the point. :: - - clf() - -You can also specify 'o' for big dots.:: - - plot(L,tsquare,'o') - - clf() - - -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. - - - - - -.. #[[Anoop: Make sure code is correct, corrected plot(L,t,o) to - plot(L,t,'o')]] - - - -.. #[[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. :: - - - 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. - - -similarly we can draw the same error bar with big red dots just change -the parameters to fmt to '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.:: - - 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. - - - - - - - -{{{ Show Summary Slide }}} - -In this tutorial we have learnt : - - - -1. How to declare a sequence of numbers. - -2. Plotting experimental data. - -#. The various options available for plotting dots instead of lines. - -#. 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. - -Thank You! - diff -r 88a01948450d -r d33698326409 plotting-data/slides.org --- a/plotting-data/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,200 +0,0 @@ -#+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 Experimental Data -#+AUTHOR: FOSSEE -#+DATE: 2010-09-14 Tue -#+EMAIL: info@fossee.in - -#+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 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 - - | L | T | - | 0.1 | 0.69 | - | 0.2 | 0.90 | - | 0.3 | 1.19 | - | 0.4 | 1.30 | - | 0.5 | 1.47 | - | 0.6 | 1.58 | - | 0.7 | 1.77 | - | 0.8 | 1.83 | - | 0.9 | 1.94 | - - -* Initializing L & T - : 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] - - - -* Question 1 - - Plot the given experimental data with large dots. - The data is on your screen. - - -* 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 | - | 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 | - - -* Plotting Error bar - - : 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 88a01948450d -r d33698326409 plotting-data/slides.tex --- a/plotting-data/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,313 +0,0 @@ -% Created 2010-11-10 Wed 02:09 -\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{Plotting Experimental Data} -\author{FOSSEE} -\date{2010-09-14 Tue} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\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{Simple Pendulum Data} -\label{sec-2} - - - - -\begin{center} -\begin{tabular}{rr} - L & T \\ - 0.1 & 0.69 \\ - 0.2 & 0.90 \\ - 0.3 & 1.19 \\ - 0.4 & 1.30 \\ - 0.5 & 1.47 \\ - 0.6 & 1.58 \\ - 0.7 & 1.77 \\ - 0.8 & 1.83 \\ - 0.9 & 1.94 \\ -\end{tabular} -\end{center} - - - -\end{frame} -\begin{frame}[fragile] -\frametitle{Initializing L \& T} -\label{sec-3} - -\begin{verbatim} - 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{Solution 1} -\label{sec-6} - - -\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] - 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} - - 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{Solution 2} -\label{sec-9} - - -\begin{verbatim} - 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-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.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} - - - - -\end{frame} -\begin{frame}[fragile] -\frametitle{Plotting Error bar} -\label{sec-11} - - -\begin{verbatim} - 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 88a01948450d -r d33698326409 plotting_data.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting_data.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,137 @@ +Plotting Experimental Data +============================= +Hello and welcome , this tutorial on Plotting Experimental data is +presented by the fossee team. + +{{{ Show the slide containing title }}} + + +{{{ Show the Outline Slide }}} + +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 +sequence. + +3. We will also see how we can use our graph to indicate Error. + +One needs to be fimiliar with the concepts of plotting +mathematical functions in Python. + +We will use data from a Simple Pendulum Experiment to illustrate our +points. + +{{{ Simple Pendulum data Slide }}} + + + + +As we know for a simple pendulum length,L is directly proportional to +the square of time,T. We shall be plotting L and T^2 values. + + +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 + +L,t type in ipython shell. :: + + 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] + + + +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) + + array([ 0.4761, 0.81 , 1.4161, 1.69 , 2.1609, 2.4964, 3.1329, + 3.3489, 3.7636]) + + +Now to plot L vs T^2 we will simply type :: + + In []: plot(L,t,.) + +'.' here represents to plot use small dots for the point. :: + + In []: clf() + +You can also specify 'o' for big dots.:: + + In []: plot(L,t,o) + + In []: clf() + + +{{{ Slide with Error data included }}} + + +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 :: + + 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] + + + +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.') + +This gives a plot with error bar for x and y axis. The dots are of +blue color. + + +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') + + + +thats it. you can explore other options to errorbar using the documentation +of errorbar.:: + + In []: errorbar? + + +{{{ Summary Slides }}} + +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. + +3. 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. + + + {{{ Show the "sponsored by FOSSEE" slide }}} + + + +This tutorial was created as a part of FOSSEE project. + +Hope you have enjoyed and found it useful. + + Thankyou + + + +Author : Amit Sethi +Internal Reviewer : +Internal Reviewer 2 : diff -r 88a01948450d -r d33698326409 plotting_data/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting_data/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,73 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. How do you declare a sequence of numbers in python? + Give example . + + Comma seperated numbers inside two square brackets. + + seq=[1.5,3.2,8.7] + + +2. Square the following sequence? + + distance_values=[2.1,4.6,8.72,9.03]. + + square(distance_values) + + + +3. How do you plot the data as points using plot function? + + By passing an extra parameter '.'. + +.. #[[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. + +6. How do I get large red colour dots on a plot? + + By passing the paramter 'ro'. + +7. What are the parameters 'xerr' and 'yerr' in errorbar function for? + + xerr - List of error values of variable on x axis. + yerr - List of error values of variable on y ayis. + +8. How would you plot error bar with a line? + + The fmt parameter for a line will be '-'. + + + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Plot an errorbar for following experimental data. + + | X | Y | Xerr | Yerr | + | 154.9 | 8106 | 8.51 | 165.8 | + | 154.3 | 8138 | 8.50 | 166.3 | + | 148.7 | 8148 | 7.78 | 161.2 | + | 149.6 | 8171 | 7.81 | 162.6 | + +in red colour with large dots + +2. List the parameters for errorbar and their function? diff -r 88a01948450d -r d33698326409 plotting_data/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting_data/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,15 @@ +Creating a Sequence:\\ +{\ex \lstinline| L = [0.1, 0.2, 0.3] |} + +Squaring a sequence:\\ +{\ex \lstinline| tsquare=square(t) |} + +Plotting two list using small dots:\\ +{\ex \lstinline| plot(L,tsquare,'.') |} + +Plotting two list using big dots:\\ +{\ex \lstinline| plot(L,tsquare,'o') |} + +Plotting an errorbar in blue color:\\ +{\ex \lstinline| errorbar(L,tsquare,xerr=delta_L, yerr=delta_T, fmt='b.') |} + diff -r 88a01948450d -r d33698326409 plotting_data/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting_data/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,218 @@ +.. Objectives +.. ---------- + +.. By the end of this tutorial, you will be able to + +.. 1. Defining a list of numbers +.. 2. Squaring a list of numbers +.. 3. Plotting data points. +.. 4. Plotting errorbars. + + +.. Prerequisites +.. ------------- + +.. 1. getting started with plotting + + +.. Author : Amit + 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 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 familiar with elementwise squaring of such a +sequence. + +3. How to plot data points using python. + +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. + +.. #[[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 +the square of time,T. We shall be plotting L and T^2 values. + + +First we will have to initiate L and T values. We initiate them as sequence +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. + +.. #[[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]] + +{{{ 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 +with argument t.This is saved into the variable tsquare.:: + + 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 :: + + plot(L,tsquare,'.') + +.. #[[Anoop: be consistent with the spacing and all.]] + +'.' here represents to plot use small dots for the point. :: + + clf() + +You can also specify 'o' for big dots.:: + + plot(L,tsquare,'o') + + clf() + + +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. + + + + + +.. #[[Anoop: Make sure code is correct, corrected plot(L,t,o) to + plot(L,t,'o')]] + + + +.. #[[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. :: + + + 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. + + +similarly we can draw the same error bar with big red dots just change +the parameters to fmt to '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.:: + + 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. + + + + + + + +{{{ Show Summary Slide }}} + +In this tutorial we have learnt : + + + +1. How to declare a sequence of numbers. + +2. Plotting experimental data. + +#. The various options available for plotting dots instead of lines. + +#. 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. + +Thank You! + diff -r 88a01948450d -r d33698326409 plotting_data/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting_data/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,200 @@ +#+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 Experimental Data +#+AUTHOR: FOSSEE +#+DATE: 2010-09-14 Tue +#+EMAIL: info@fossee.in + +#+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 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 + + | L | T | + | 0.1 | 0.69 | + | 0.2 | 0.90 | + | 0.3 | 1.19 | + | 0.4 | 1.30 | + | 0.5 | 1.47 | + | 0.6 | 1.58 | + | 0.7 | 1.77 | + | 0.8 | 1.83 | + | 0.9 | 1.94 | + + +* Initializing L & T + : 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] + + + +* Question 1 + - Plot the given experimental data with large dots. + The data is on your screen. + + +* 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 | + | 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 | + + +* Plotting Error bar + + : 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 88a01948450d -r d33698326409 plotting_data/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting_data/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,313 @@ +% Created 2010-11-10 Wed 02:09 +\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{Plotting Experimental Data} +\author{FOSSEE} +\date{2010-09-14 Tue} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\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{Simple Pendulum Data} +\label{sec-2} + + + + +\begin{center} +\begin{tabular}{rr} + L & T \\ + 0.1 & 0.69 \\ + 0.2 & 0.90 \\ + 0.3 & 1.19 \\ + 0.4 & 1.30 \\ + 0.5 & 1.47 \\ + 0.6 & 1.58 \\ + 0.7 & 1.77 \\ + 0.8 & 1.83 \\ + 0.9 & 1.94 \\ +\end{tabular} +\end{center} + + + +\end{frame} +\begin{frame}[fragile] +\frametitle{Initializing L \& T} +\label{sec-3} + +\begin{verbatim} + 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{Solution 1} +\label{sec-6} + + +\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] + 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} + + 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{Solution 2} +\label{sec-9} + + +\begin{verbatim} + 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-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.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} + + + + +\end{frame} +\begin{frame}[fragile] +\frametitle{Plotting Error bar} +\label{sec-11} + + +\begin{verbatim} + 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 88a01948450d -r d33698326409 savefig/questions.rst --- a/savefig/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,123 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - - -1. What argument can be used with savefig to increase the resolution - of the plot while saving a plot. - - a. fname - #. transparency - #. dpi - #. format - -Answer: dpi - -2. The fname argument of savefig has to be always absolute path. - - a. True - #. False - -Answer: False - -3. You are right now in the directory `/home/fossee`, from the - following which one is the correct one in-order to save the plot as - svg with the filename `plot` to the directory `/home/fossee/sine/` - - a. savefig('/sine/plot.svg') - #. savefig('sine/plot.svg') - #. savefig('home/fossee/sine/plot.svg') - #. All of these - #. None of the above - -Answer: savefig('sine/plot.svg') - -4. Which is the best image format to be used with Latex documents - which savefig supports? - - a. SVG - Scalable Vector Graphics - #. EPS - Encapsulated Post Script - #. PS - Post Script - #. PNG - Portable Network Graphics - #. None of the above - -Answer: EPS - Encapsulated Post Script - -5. ``savefig('sine.png')`` saves the plot in, - - a. The root directory ``/`` (on GNU/Linux, Unix based systems) - ``c:\`` (on windows). - #. Will result in an error as full path is not supplied. - #. The current working directory. - #. Predefined directory like ``/documents``. - -Answer: The current working directory. - -6. Study the following code and tell what will happen, - :: - savefig('cosine.png',facecolor='blue') - - a. Will generate an error as plot statements are missing - #. Will generate an error as full path is not specified - #. Create a file ``cosine.png`` with blue background at the current - working directory. - #. Create a file ``cosine.png`` with blue background at a - predefined directory like ``/documents``. - -Answer: Create a file ``cosine.png`` with blue background at the - current working directory. - -7. How to save the below plot as ``sine_green_border.png`` with green - color border/edge in the current working directory. The plot is given - as, - :: - x = linspace(-5*pi,5*pi,200) - plot(x,sin(x),linewidth=2) - legend(['sin(x)']) - - a. ``savefig('sine_green_border.png',bordercolor='green')`` - #. ``savefig('sine_green_border.png',facecolor='green')`` - #. ``savefig('sine_green_border.png',edgecolor='green')`` - #. ``savefig('/sine_green_border.png',bordercolor='green')`` - -Answer: savefig('sine_green_border.png',edgecolor='green') - -8. Given the below code snippet, what does it do? - :: - x = linspace(-5*pi,5*pi,200) - plot(x,sin(x),linewidth=2) - legend(['sin(x)']) - savefig('sine.png',format='pdf',papertype='a4') - - a. Save the sine plot in file sine.png as a pdf file in page-size - A4 and saves it into the current working directory - #. Save the sine plot in file sine.png.pdf in page-size A4 into the - current working directory. - #. Save the sine plot in a file sine.png in png format with - page-size A4 in the current working directory overriding the - format argument - #. Error in filename and format mismatch. - -Answer: Save the sine plot in file sine.png as a pdf file in page-size - A4 and saves it into the current working directory - -.. #[Puneeth: Good questions, but can we use it in quiz? most of it -.. has not been taught in the tutorial.] - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Plot a cosine plot from -2pi to 2pi in green color taking 300 - points. Title the plot as 'Cosine plot' and the legend plot with - 'cos(x)'. And save the plot as a pdf file with the filename - cosine_plot. - -2. Plot tan(x) where x varies from -4pi to 4pi in red color taking 600 - points. Title the plot as 'Tan plot' and the legend plot with - 'tan(x)'. And save the plot as a svg file with the filename - tangent_plot. - - diff -r 88a01948450d -r d33698326409 savefig/quickref.tex --- a/savefig/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,5 +0,0 @@ -Saving a plot(png):\\ -{\ex \lstinline| savefig('filename.png')|} - -Saving a plot(pdf):\\ -{\ex \lstinline| savefig('filename.pdf')|} diff -r 88a01948450d -r d33698326409 savefig/script.rst --- a/savefig/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,163 +0,0 @@ -.. Objectives -.. ---------- - -.. At the end of this tutorial, you will be able to - -.. 1. Save plots using ``savefig()`` function. -.. #. Save plots in different formats. - - -.. Prerequisites -.. ------------- - -.. 1. should have ``ipython`` and ``pylab`` installed. -.. #. getting started with ``ipython``. -.. #. using plot command interactively. - -.. Author : Anoop Jacob Thomas - Internal Reviewer : Puneeth - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <10-11-2010, Anand, OK> [2010-10-05] - -.. #[Puneeth: Quickref missing.] - -======= -Savefig -======= - -{{{ Show the first slide }}} - -Hello and welcome to the tutorial saving plots. - -{{{ switch to next slide, outline slide }}} - -In this tutorial you will learn how to save plots using Python, saving -in different formats, and locating the file in the file system. - -.. #[Puneeth: file-system is too technical.] - -{{{ switch to next slide, a sine wave}}} - -Start your IPython interpreter with the command :: - - ipython -pylab - -As you know, it will start your IPython interpreter with the required -python modules for plotting and saving your plots. - -{{{ Open ipython }}} - -Now let us plot something, let us plot a sine wave from minus 3 pi to -3 pi. Let us start by calculating the required points for the plot. It -can be done using linspace as, :: - - x = linspace(-3*pi,3*pi,100) - -We have stored required points in x. Now let us plot the points using -the statement :: - - plot(x,sin(x)) - -{{{ Keep the plot open }}} - -Done! we have made a very basic sine plot, now let us see how to save -the plot for future use so that you can embed the plot in your -reports. - -.. #[Puneeth: All this is known stuff. You don't have to elaborate so -.. much on it. Just say, let us plot sin function from -3 pi to 3 -.. pi. Show the commands, and be done with it. ] - -{{{ switch to next slide, savefig() }}} - -{{{ Switch the focus to IPython interpreter window }}} - -For saving the plot, we will use ``savefig()`` function, and it has to be -done with the plot window open. The statement is, :: - - savefig('/home/fossee/sine.png') - -Notice that ``savefig`` function takes one argument which is the -filename. The last 3 characters after the ``.`` in the filename is the -extension or type of the file which determines the format in which you -want to save. - -.. #[Puneeth: removed mention of string] - -.. #[[Anoop: I think this treatment is better :) ]] - -{{{ Highlight the /home/fossee part using mouse movements }}} - -Also, note that we gave the full path or the absolute path to which we -want to save the file. - -{{{ Highlight the .png part using mouse movements }}} - -Here I have used an extension ``.png`` which means I want to save the -image as a PNG file. - -Now let us locate ``sine.png`` file saved. We saved the file to -``/home/fossee`` so let us navigate to ``/home/fossee`` using the -file browser. - -{{{ Open the browser, navigate to /home/fossee and highlight the file -sine.png }}} - -Yes, the file ``sine.png`` is here and let us check it. - -{{{ Open the file sine.png and show it for two-three seconds and then -close it and return to IPython interpreter, make sure the plot window -is still open, also don't close the file browser window }}} - -{{{ switch to next slide, More on savefig() }}} - -So in-order to save a plot, we use ``savefig`` function. ``savefig`` -can save the plot in many formats, such as pdf - portable document -format, ps - post script, eps - encapsulated post script, svg - -scalable vector graphics, png - portable network graphics which -support transparency etc. - -.. #[[slide must give the extensions for the files - Anoop]] - -{{{ switch to next slide, exercise 1 }}} - -Let us now try to save the plot in eps format. ``eps`` stands for -encapsulated post script, and it can be embedded in your latex -documents. Pause here and try to figure it out yourself. - -{{{ Switch focus to the already open plot window }}} - -We still have the sine plot with us, and now let us save the plot as -``sine.eps``. - -{{{ switch to next slide, solution 1 }}} - -{{{ Switch focus to IPython interpreter }}} - -Now, We will save the plot using the function ``savefig`` :: - - savefig('/home/fossee/sine.eps') - -{{{ Switch focus to file browser window }}} - -Now let us go to ``/home/fossee`` and see the new file created. - -{{{ Highlight the file sine.eps with a single mouse click for 2 -seconds and then double click and open the file }}} - -Yes! the new file ``sine.eps`` is here. - -{{{ switch to next slide, exercise 2 }}} - -Now you may try saving the same in pdf, ps, svg formats. - -{{{ Switch to summary slide }}} - -This brings us to the end of this tutorial, in this tutorial we -learned to save plots using the function ``savefig()``. Saving the -plots in different formats and locating the files in the file system. - -{{{ switch to Thank you slide }}} - -Thank you! diff -r 88a01948450d -r d33698326409 savefig/slides.org --- a/savefig/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,99 +0,0 @@ -#+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: Savefig -#+AUTHOR: FOSSEE -#+EMAIL: info@fossee.in -#+DATE: 2010-10-11 Mon - -#+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 - - Saving plots. - - Plotting in different formats. - - Locating the file in the file system. - -* Creating a basic plot - Plot a sine wave from -3pi to 3pi. - #+begin_src python - In []: x = linspace(-3*pi,3*pi,100) - - In []: plot(x, sin(x)) - #+end_src -* savefig() -** savefig() - to save plots - : syntax: savefig(fname) -** example -*** savefig('/home/fossee/sine.png') - - file sine.png saved to the folder /home/fossee - - .png - file type - -* More on savefig() -** Recall - - .png - file type -** File types supported -*** .pdf - PDF(Portable Document Format) -*** .ps - PS(Post Script) -*** .eps - Encapsulated Post Script - ~to be used with~ LaTeX ~documents~ -*** .svg - Scalable Vector Graphics - ~vector graphics~ -*** .png - Portable Network Graphics - ~supports transparency~ -* Exercise 1 - Save the sine plot in the format EPS which can be embedded in LaTeX documents. -* Solution 1 - #+begin_src python - savefig('/home/fossee/sine.eps') - #+end_src -* Exercise 2 - Save the sine plot in PDF, PS and SVG formats. - -* Summary - You should now be able to - - Use ~savefig()~ function - - Save plots in different formats - - PDF - - PS - - PNG - - SVG - - EPS - - Locating the files in file system. - -* 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 88a01948450d -r d33698326409 savefig/slides.tex --- a/savefig/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,185 +0,0 @@ -% Created 2010-10-11 Mon 17:08 -\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{Savefig} -\author{FOSSEE} -\date{2010-10-11 Mon} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Saving plots. -\item Plotting in different formats. -\item Locating the file in the file system. -\end{itemize} -\end{frame} -\begin{frame}[fragile] -\frametitle{Creating a basic plot} -\label{sec-2} - - Plot a sine wave from -3pi to 3pi. -\begin{verbatim} -In []: x = linspace(-3*pi,3*pi,100) - -In []: plot(x, sin(x)) -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{savefig()} -\label{sec-3} -\begin{itemize} - -\item savefig() - to save plots -\label{sec-3_1}% -\begin{verbatim} - syntax: savefig(fname) -\end{verbatim} - - -\item example -\label{sec-3_2}% -\begin{itemize} - -\item savefig('/home/fossee/sine.png') -\label{sec-3_2_1}% -\begin{itemize} -\item file sine.png saved to the folder /home/fossee -\item .png - file type -\end{itemize} - - -\end{itemize} % ends low level -\end{itemize} % ends low level -\end{frame} -\begin{frame} -\frametitle{More on savefig()} -\label{sec-4} -\begin{itemize} - -\item Recall -\label{sec-4_1}% -\begin{itemize} -\item .png - file type -\end{itemize} - - -\item File types supported -\label{sec-4_2}% -\begin{itemize} - -\item .pdf - PDF(Portable Document Format)\\ -\label{sec-4_2_1}% -\item .ps - PS(Post Script)\\ -\label{sec-4_2_2}% -\item .eps - Encapsulated Post Script\\ -\label{sec-4_2_3}% -\texttt{to be used with} \LaTeX{} \texttt{documents} - -\item .svg - Scalable Vector Graphics\\ -\label{sec-4_2_4}% -\texttt{vector graphics} - -\item .png - Portable Network Graphics\\ -\label{sec-4_2_5}% -\texttt{supports transparency} -\end{itemize} % ends low level -\end{itemize} % ends low level -\end{frame} -\begin{frame} -\frametitle{Exercise 1} -\label{sec-5} - - Save the sine plot in the format EPS which can be embedded in \LaTeX{} documents. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 1} -\label{sec-6} - -\begin{verbatim} -savefig('/home/fossee/sine.eps') -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Exercise 2} -\label{sec-7} - - Save the sine plot in PDF, PS and SVG formats. -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-8} - - You should now be able to -\begin{itemize} -\item Use \texttt{savefig()} function -\item Save plots in different formats - -\begin{itemize} -\item PDF -\item PS -\item PNG -\item SVG -\item EPS -\end{itemize} - -\item Locating the files in file system. -\end{itemize} - - -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-9} - - \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 88a01948450d -r d33698326409 saving_plots/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/saving_plots/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,123 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + + +1. What argument can be used with savefig to increase the resolution + of the plot while saving a plot. + + a. fname + #. transparency + #. dpi + #. format + +Answer: dpi + +2. The fname argument of savefig has to be always absolute path. + + a. True + #. False + +Answer: False + +3. You are right now in the directory `/home/fossee`, from the + following which one is the correct one in-order to save the plot as + svg with the filename `plot` to the directory `/home/fossee/sine/` + + a. savefig('/sine/plot.svg') + #. savefig('sine/plot.svg') + #. savefig('home/fossee/sine/plot.svg') + #. All of these + #. None of the above + +Answer: savefig('sine/plot.svg') + +4. Which is the best image format to be used with Latex documents + which savefig supports? + + a. SVG - Scalable Vector Graphics + #. EPS - Encapsulated Post Script + #. PS - Post Script + #. PNG - Portable Network Graphics + #. None of the above + +Answer: EPS - Encapsulated Post Script + +5. ``savefig('sine.png')`` saves the plot in, + + a. The root directory ``/`` (on GNU/Linux, Unix based systems) + ``c:\`` (on windows). + #. Will result in an error as full path is not supplied. + #. The current working directory. + #. Predefined directory like ``/documents``. + +Answer: The current working directory. + +6. Study the following code and tell what will happen, + :: + savefig('cosine.png',facecolor='blue') + + a. Will generate an error as plot statements are missing + #. Will generate an error as full path is not specified + #. Create a file ``cosine.png`` with blue background at the current + working directory. + #. Create a file ``cosine.png`` with blue background at a + predefined directory like ``/documents``. + +Answer: Create a file ``cosine.png`` with blue background at the + current working directory. + +7. How to save the below plot as ``sine_green_border.png`` with green + color border/edge in the current working directory. The plot is given + as, + :: + x = linspace(-5*pi,5*pi,200) + plot(x,sin(x),linewidth=2) + legend(['sin(x)']) + + a. ``savefig('sine_green_border.png',bordercolor='green')`` + #. ``savefig('sine_green_border.png',facecolor='green')`` + #. ``savefig('sine_green_border.png',edgecolor='green')`` + #. ``savefig('/sine_green_border.png',bordercolor='green')`` + +Answer: savefig('sine_green_border.png',edgecolor='green') + +8. Given the below code snippet, what does it do? + :: + x = linspace(-5*pi,5*pi,200) + plot(x,sin(x),linewidth=2) + legend(['sin(x)']) + savefig('sine.png',format='pdf',papertype='a4') + + a. Save the sine plot in file sine.png as a pdf file in page-size + A4 and saves it into the current working directory + #. Save the sine plot in file sine.png.pdf in page-size A4 into the + current working directory. + #. Save the sine plot in a file sine.png in png format with + page-size A4 in the current working directory overriding the + format argument + #. Error in filename and format mismatch. + +Answer: Save the sine plot in file sine.png as a pdf file in page-size + A4 and saves it into the current working directory + +.. #[Puneeth: Good questions, but can we use it in quiz? most of it +.. has not been taught in the tutorial.] + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Plot a cosine plot from -2pi to 2pi in green color taking 300 + points. Title the plot as 'Cosine plot' and the legend plot with + 'cos(x)'. And save the plot as a pdf file with the filename + cosine_plot. + +2. Plot tan(x) where x varies from -4pi to 4pi in red color taking 600 + points. Title the plot as 'Tan plot' and the legend plot with + 'tan(x)'. And save the plot as a svg file with the filename + tangent_plot. + + diff -r 88a01948450d -r d33698326409 saving_plots/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/saving_plots/quickref.tex Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 saving_plots/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/saving_plots/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,163 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Save plots using ``savefig()`` function. +.. #. Save plots in different formats. + + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` and ``pylab`` installed. +.. #. getting started with ``ipython``. +.. #. using plot command interactively. + +.. Author : Anoop Jacob Thomas + Internal Reviewer : Puneeth + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <10-11-2010, Anand, OK> [2010-10-05] + +.. #[Puneeth: Quickref missing.] + +======= +Savefig +======= + +{{{ Show the first slide }}} + +Hello and welcome to the tutorial saving plots. + +{{{ switch to next slide, outline slide }}} + +In this tutorial you will learn how to save plots using Python, saving +in different formats, and locating the file in the file system. + +.. #[Puneeth: file-system is too technical.] + +{{{ switch to next slide, a sine wave}}} + +Start your IPython interpreter with the command :: + + ipython -pylab + +As you know, it will start your IPython interpreter with the required +python modules for plotting and saving your plots. + +{{{ Open ipython }}} + +Now let us plot something, let us plot a sine wave from minus 3 pi to +3 pi. Let us start by calculating the required points for the plot. It +can be done using linspace as, :: + + x = linspace(-3*pi,3*pi,100) + +We have stored required points in x. Now let us plot the points using +the statement :: + + plot(x,sin(x)) + +{{{ Keep the plot open }}} + +Done! we have made a very basic sine plot, now let us see how to save +the plot for future use so that you can embed the plot in your +reports. + +.. #[Puneeth: All this is known stuff. You don't have to elaborate so +.. much on it. Just say, let us plot sin function from -3 pi to 3 +.. pi. Show the commands, and be done with it. ] + +{{{ switch to next slide, savefig() }}} + +{{{ Switch the focus to IPython interpreter window }}} + +For saving the plot, we will use ``savefig()`` function, and it has to be +done with the plot window open. The statement is, :: + + savefig('/home/fossee/sine.png') + +Notice that ``savefig`` function takes one argument which is the +filename. The last 3 characters after the ``.`` in the filename is the +extension or type of the file which determines the format in which you +want to save. + +.. #[Puneeth: removed mention of string] + +.. #[[Anoop: I think this treatment is better :) ]] + +{{{ Highlight the /home/fossee part using mouse movements }}} + +Also, note that we gave the full path or the absolute path to which we +want to save the file. + +{{{ Highlight the .png part using mouse movements }}} + +Here I have used an extension ``.png`` which means I want to save the +image as a PNG file. + +Now let us locate ``sine.png`` file saved. We saved the file to +``/home/fossee`` so let us navigate to ``/home/fossee`` using the +file browser. + +{{{ Open the browser, navigate to /home/fossee and highlight the file +sine.png }}} + +Yes, the file ``sine.png`` is here and let us check it. + +{{{ Open the file sine.png and show it for two-three seconds and then +close it and return to IPython interpreter, make sure the plot window +is still open, also don't close the file browser window }}} + +{{{ switch to next slide, More on savefig() }}} + +So in-order to save a plot, we use ``savefig`` function. ``savefig`` +can save the plot in many formats, such as pdf - portable document +format, ps - post script, eps - encapsulated post script, svg - +scalable vector graphics, png - portable network graphics which +support transparency etc. + +.. #[[slide must give the extensions for the files - Anoop]] + +{{{ switch to next slide, exercise 1 }}} + +Let us now try to save the plot in eps format. ``eps`` stands for +encapsulated post script, and it can be embedded in your latex +documents. Pause here and try to figure it out yourself. + +{{{ Switch focus to the already open plot window }}} + +We still have the sine plot with us, and now let us save the plot as +``sine.eps``. + +{{{ switch to next slide, solution 1 }}} + +{{{ Switch focus to IPython interpreter }}} + +Now, We will save the plot using the function ``savefig`` :: + + savefig('/home/fossee/sine.eps') + +{{{ Switch focus to file browser window }}} + +Now let us go to ``/home/fossee`` and see the new file created. + +{{{ Highlight the file sine.eps with a single mouse click for 2 +seconds and then double click and open the file }}} + +Yes! the new file ``sine.eps`` is here. + +{{{ switch to next slide, exercise 2 }}} + +Now you may try saving the same in pdf, ps, svg formats. + +{{{ Switch to summary slide }}} + +This brings us to the end of this tutorial, in this tutorial we +learned to save plots using the function ``savefig()``. Saving the +plots in different formats and locating the files in the file system. + +{{{ switch to Thank you slide }}} + +Thank you! diff -r 88a01948450d -r d33698326409 saving_plots/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/saving_plots/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,99 @@ +#+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: Savefig +#+AUTHOR: FOSSEE +#+EMAIL: info@fossee.in +#+DATE: 2010-10-11 Mon + +#+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 + - Saving plots. + - Plotting in different formats. + - Locating the file in the file system. + +* Creating a basic plot + Plot a sine wave from -3pi to 3pi. + #+begin_src python + In []: x = linspace(-3*pi,3*pi,100) + + In []: plot(x, sin(x)) + #+end_src +* savefig() +** savefig() - to save plots + : syntax: savefig(fname) +** example +*** savefig('/home/fossee/sine.png') + - file sine.png saved to the folder /home/fossee + - .png - file type + +* More on savefig() +** Recall + - .png - file type +** File types supported +*** .pdf - PDF(Portable Document Format) +*** .ps - PS(Post Script) +*** .eps - Encapsulated Post Script + ~to be used with~ LaTeX ~documents~ +*** .svg - Scalable Vector Graphics + ~vector graphics~ +*** .png - Portable Network Graphics + ~supports transparency~ +* Exercise 1 + Save the sine plot in the format EPS which can be embedded in LaTeX documents. +* Solution 1 + #+begin_src python + savefig('/home/fossee/sine.eps') + #+end_src +* Exercise 2 + Save the sine plot in PDF, PS and SVG formats. + +* Summary + You should now be able to + - Use ~savefig()~ function + - Save plots in different formats + - PDF + - PS + - PNG + - SVG + - EPS + - Locating the files in file system. + +* 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 88a01948450d -r d33698326409 saving_plots/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/saving_plots/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,185 @@ +% Created 2010-10-11 Mon 17:08 +\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{Savefig} +\author{FOSSEE} +\date{2010-10-11 Mon} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Saving plots. +\item Plotting in different formats. +\item Locating the file in the file system. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Creating a basic plot} +\label{sec-2} + + Plot a sine wave from -3pi to 3pi. +\begin{verbatim} +In []: x = linspace(-3*pi,3*pi,100) + +In []: plot(x, sin(x)) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{savefig()} +\label{sec-3} +\begin{itemize} + +\item savefig() - to save plots +\label{sec-3_1}% +\begin{verbatim} + syntax: savefig(fname) +\end{verbatim} + + +\item example +\label{sec-3_2}% +\begin{itemize} + +\item savefig('/home/fossee/sine.png') +\label{sec-3_2_1}% +\begin{itemize} +\item file sine.png saved to the folder /home/fossee +\item .png - file type +\end{itemize} + + +\end{itemize} % ends low level +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{More on savefig()} +\label{sec-4} +\begin{itemize} + +\item Recall +\label{sec-4_1}% +\begin{itemize} +\item .png - file type +\end{itemize} + + +\item File types supported +\label{sec-4_2}% +\begin{itemize} + +\item .pdf - PDF(Portable Document Format)\\ +\label{sec-4_2_1}% +\item .ps - PS(Post Script)\\ +\label{sec-4_2_2}% +\item .eps - Encapsulated Post Script\\ +\label{sec-4_2_3}% +\texttt{to be used with} \LaTeX{} \texttt{documents} + +\item .svg - Scalable Vector Graphics\\ +\label{sec-4_2_4}% +\texttt{vector graphics} + +\item .png - Portable Network Graphics\\ +\label{sec-4_2_5}% +\texttt{supports transparency} +\end{itemize} % ends low level +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Exercise 1} +\label{sec-5} + + Save the sine plot in the format EPS which can be embedded in \LaTeX{} documents. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-6} + +\begin{verbatim} +savefig('/home/fossee/sine.eps') +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Exercise 2} +\label{sec-7} + + Save the sine plot in PDF, PS and SVG formats. +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-8} + + You should now be able to +\begin{itemize} +\item Use \texttt{savefig()} function +\item Save plots in different formats + +\begin{itemize} +\item PDF +\item PS +\item PNG +\item SVG +\item EPS +\end{itemize} + +\item Locating the files in file system. +\end{itemize} + + +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-9} + + \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 88a01948450d -r d33698326409 testing-debugging/questions.rst --- a/testing-debugging/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,60 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. Why do we do Software Testing? - - Answer: To evaluate a program and determine that it meets required results. - - - - -2. What is proper indentation for python code according to style guidelines? - - Answer: Four Space Indentation - -3. What is the idiom used for running python scripts in a standalone manner? - - Answer: - if __name__ == '__main__': - -4. What constitutes a test case? - - Answer: A set of inputs and expected result - -5. How do you start the debugger on ipython? - - Answer: %debug - -6. What idiom do you use for catching and exception? - - Answer: try,catch. - -7. What kind of exception is 0/0? - - Answer Zero Division Error - -8. a = 12.68 - b = 0.05 - c = round(a/b) - d = c * b - - What would you recommend to the programmer who wrote - above written piece of code. - - - - - - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Write a program for checking if two numbers are coprime - Create test cases for it and automate it. -2. Write a program that divides two numbers. Take the numbers from the user. Also make sure the code tell the user that input is invalid incase the divisor is 0. - - diff -r 88a01948450d -r d33698326409 testing-debugging/quickref.tex --- a/testing-debugging/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,28 +0,0 @@ -Skeleton of a test:\\ -{\ex \lstinline| if __name__ == '__main__':|} -{\ex \lstinline| result = gcd(48, 64) |} -{\ex \lstinline| if result != 16: |} -{\ex \lstinline| print ``Test Failed'' |} -{\ex \lstinline| print ``Test Passed'' |} - - -\textbf{Testing} - -Get results from function or unit of code being tested.Compare it to original output. Test passed if they match else failed. - -\textbf{Code Style} -Four Space Indentation -79 character limit on a line -Funtions should be seperated by -blank line -Use Docstring -White space around operators - -Skeleton of try catch:\\ -{\ex \lstinline| try: |} -{\ex \lstinline| num = int(a) |} -{\ex \lstinline| except: |} -{\ex \lstinline| print ``Wrong input...'' |} - -Starting debugger in ipython:\\ -{\ex \lstinline| %debug |} diff -r 88a01948450d -r d33698326409 testing-debugging/script.rst --- a/testing-debugging/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,316 +0,0 @@ -.. 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" - 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. - 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 following -code - c=a/b - - -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. - - - -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. - - - -Lets see another example of debugging. Create a file mymodule.py and -add the following code:: - - def test(): - total=1+1 - print spam - - - -Lets now try and run this code :: - - import mymodule - mymodule.test() - - -{{{ Slide with idb and total being accessed }}} - -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 88a01948450d -r d33698326409 testing-debugging/slides.org --- a/testing-debugging/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,209 +0,0 @@ -#+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_src python - def gcd(a, b): - if a % b == 0: - return b - return gcd(b, a%b) -#+end_src python - -* Test for gcd.py - - Edit gcd.py file -#+begin_src 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_src - -* Automating tests -#+begin_src 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_src - -* Question 1 - For the same inputs as gcd write automated tests for LCM. -* Solution 1 -#+begin_src python - def gcd(a, b): - if a % b == 0: - return b - return gcd(b, a%b) - - def lcm(a, b): - return (a * b) / gcd(a, b) - - if __name__ == '__main__': - for line in open('lcmtestcases.txt'): - numbers = line.split() - x = int(numbers[0]) - y = int(numbers[1]) - result = int(numbers[2]) - if lcm(x, y) != result: - print "Failed lcm test for", x, y - -#+end_src - -* Meaning full names -#+begin_src python - - amount = 12.68 - denom = 0.05 - nCoins = round(amount / denom) - rAmount = nCoins * denom - -#+end_src - -* Code style - - Four Space Indentation - - 79 character limit on a line - - Funtions should be seperated by - blank line - - Use Docstring - - White space around operators - - l = 32 % 4 - -* Question 2 - - Give meaningful names to the variables in following - code - - - c = a / b - -* Solution 2 -#+begin_src python - - quotient = dividend / divisor - -#+end_src - -* Code Snippet -#+begin_src python - - while True print 'Hello world' - -#+end_src - -* Error -#+begin_latex -\begin{lstlisting} - while True print 'Hello world' - \end{lstlisting} - \begin{lstlisting} - File "", line 1, in ? - while True print 'Hello world' -SyntaxError: invalid syntax -\end{lstlisting} -#+end_latex - -* Code Snippet -#+begin_src python - a = raw_input("Enter a number") - try: - num = int(a) - except: - print "Wrong input ..." - -#+end_src - -* Using idb -#+begin_latex -\small -\begin{lstlisting} -In []: import mymodule -In []: mymodule.test() ---------------------------------------------- -NameError Traceback (most recent call last) - in () -mymodule.py in test() - 1 def test(): - 2 total=1+1 -----> 3 print spam -NameError: global name 'spam' is not defined - -In []: %debug -> mymodule.py(2)test() - 0 print spam -ipdb> total -2 -\end{lstlisting} - -#+end_latex - - - -* Summary - - Create simple tests for a function. - - Learn to Automate tests using many predefined test cases. - - Good coding standards. - - Difference between syntax error and exception. - - Handling exception using try and except. - - Using %debug for debugging on ipython. - -* 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 88a01948450d -r d33698326409 testing-debugging/slides.tex --- a/testing-debugging/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,278 +0,0 @@ -% Created 2010-11-12 Fri 02:00 -\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{verbatim} -def gcd(a, b): - if a % b == 0: - return b - return gcd(b, a%b) -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Test for gcd.py} -\label{sec-3} - -\begin{itemize} -\item Edit gcd.py file -\end{itemize} - -\begin{verbatim} -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{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Automating tests} -\label{sec-4} - -\begin{verbatim} -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{verbatim} -\end{frame} -\begin{frame} -\frametitle{Question 1} -\label{sec-5} - - For the same inputs as gcd write automated tests for LCM. -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 1} -\label{sec-6} - -\begin{verbatim} -def gcd(a, b): - if a % b == 0: - return b - return gcd(b, a%b) - - def lcm(a, b): - return (a * b) / gcd(a, b) - - if __name__ == '__main__': - for line in open('lcmtestcases.txt'): - numbers = line.split() - x = int(numbers[0]) - y = int(numbers[1]) - result = int(numbers[2]) - if lcm(x, y) != result: - print "Failed lcm test for", x, y -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Meaning full names} -\label{sec-7} - -\begin{verbatim} - -amount = 12.68 -denom = 0.05 -nCoins = round(amount / denom) -rAmount = nCoins * denom -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Code style} -\label{sec-8} - -\begin{itemize} -\item Four Space Indentation -\item 79 character limit on a line -\item Funtions should be seperated by - blank line -\item Use Docstring -\item White space around operators - -\begin{itemize} -\item l = 32 \% 4 -\end{itemize} - -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Question 2} -\label{sec-9} - -\begin{itemize} -\item Give meaningful names to the variables in following - code - -\begin{itemize} -\item c = a / b -\end{itemize} - -\end{itemize} -\end{frame} -\begin{frame}[fragile] -\frametitle{Solution 2} -\label{sec-10} - -\begin{verbatim} - -quotient = dividend / divisor -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Code Snippet} -\label{sec-11} - -\begin{verbatim} - -while True print 'Hello world' -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Error} -\label{sec-12} - -\begin{lstlisting} - while True print 'Hello world' - \end{lstlisting} - \begin{lstlisting} - File "", line 1, in ? - while True print 'Hello world' -SyntaxError: invalid syntax -\end{lstlisting} -\end{frame} -\begin{frame}[fragile] -\frametitle{Code Snippet} -\label{sec-13} - -\begin{verbatim} -a = raw_input("Enter a number") -try: - num = int(a) - except: - print "Wrong input ..." -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Using idb} -\label{sec-14} - -\small -\begin{lstlisting} -In []: import mymodule -In []: mymodule.test() ---------------------------------------------- -NameError Traceback (most recent call last) - in () -mymodule.py in test() - 1 def test(): - 2 total=1+1 -----> 3 print spam -NameError: global name 'spam' is not defined - -In []: %debug -> mymodule.py(2)test() - 0 print spam -ipdb> total -2 -\end{lstlisting} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-15} - -\begin{itemize} -\item Create simple tests for a function. -\item Learn to Automate tests using many predefined test cases. -\item Good coding standards. -\item Difference between syntax error and exception. -\item Handling exception using try and except. -\item Using \%debug for debugging on ipython. -\end{itemize} -\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 88a01948450d -r d33698326409 testing_and_debugging/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/testing_and_debugging/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,60 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Why do we do Software Testing? + + Answer: To evaluate a program and determine that it meets required results. + + + + +2. What is proper indentation for python code according to style guidelines? + + Answer: Four Space Indentation + +3. What is the idiom used for running python scripts in a standalone manner? + + Answer: + if __name__ == '__main__': + +4. What constitutes a test case? + + Answer: A set of inputs and expected result + +5. How do you start the debugger on ipython? + + Answer: %debug + +6. What idiom do you use for catching and exception? + + Answer: try,catch. + +7. What kind of exception is 0/0? + + Answer Zero Division Error + +8. a = 12.68 + b = 0.05 + c = round(a/b) + d = c * b + + What would you recommend to the programmer who wrote + above written piece of code. + + + + + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Write a program for checking if two numbers are coprime + Create test cases for it and automate it. +2. Write a program that divides two numbers. Take the numbers from the user. Also make sure the code tell the user that input is invalid incase the divisor is 0. + + diff -r 88a01948450d -r d33698326409 testing_and_debugging/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/testing_and_debugging/quickref.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,28 @@ +Skeleton of a test:\\ +{\ex \lstinline| if __name__ == '__main__':|} +{\ex \lstinline| result = gcd(48, 64) |} +{\ex \lstinline| if result != 16: |} +{\ex \lstinline| print ``Test Failed'' |} +{\ex \lstinline| print ``Test Passed'' |} + + +\textbf{Testing} + +Get results from function or unit of code being tested.Compare it to original output. Test passed if they match else failed. + +\textbf{Code Style} +Four Space Indentation +79 character limit on a line +Funtions should be seperated by +blank line +Use Docstring +White space around operators + +Skeleton of try catch:\\ +{\ex \lstinline| try: |} +{\ex \lstinline| num = int(a) |} +{\ex \lstinline| except: |} +{\ex \lstinline| print ``Wrong input...'' |} + +Starting debugger in ipython:\\ +{\ex \lstinline| %debug |} diff -r 88a01948450d -r d33698326409 testing_and_debugging/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/testing_and_debugging/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,316 @@ +.. 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" + 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. + 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 following +code + c=a/b + + +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. + + + +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. + + + +Lets see another example of debugging. Create a file mymodule.py and +add the following code:: + + def test(): + total=1+1 + print spam + + + +Lets now try and run this code :: + + import mymodule + mymodule.test() + + +{{{ Slide with idb and total being accessed }}} + +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 88a01948450d -r d33698326409 testing_and_debugging/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/testing_and_debugging/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,209 @@ +#+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_src python + def gcd(a, b): + if a % b == 0: + return b + return gcd(b, a%b) +#+end_src python + +* Test for gcd.py + - Edit gcd.py file +#+begin_src 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_src + +* Automating tests +#+begin_src 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_src + +* Question 1 + For the same inputs as gcd write automated tests for LCM. +* Solution 1 +#+begin_src python + def gcd(a, b): + if a % b == 0: + return b + return gcd(b, a%b) + + def lcm(a, b): + return (a * b) / gcd(a, b) + + if __name__ == '__main__': + for line in open('lcmtestcases.txt'): + numbers = line.split() + x = int(numbers[0]) + y = int(numbers[1]) + result = int(numbers[2]) + if lcm(x, y) != result: + print "Failed lcm test for", x, y + +#+end_src + +* Meaning full names +#+begin_src python + + amount = 12.68 + denom = 0.05 + nCoins = round(amount / denom) + rAmount = nCoins * denom + +#+end_src + +* Code style + - Four Space Indentation + - 79 character limit on a line + - Funtions should be seperated by + blank line + - Use Docstring + - White space around operators + - l = 32 % 4 + +* Question 2 + - Give meaningful names to the variables in following + code + + - c = a / b + +* Solution 2 +#+begin_src python + + quotient = dividend / divisor + +#+end_src + +* Code Snippet +#+begin_src python + + while True print 'Hello world' + +#+end_src + +* Error +#+begin_latex +\begin{lstlisting} + while True print 'Hello world' + \end{lstlisting} + \begin{lstlisting} + File "", line 1, in ? + while True print 'Hello world' +SyntaxError: invalid syntax +\end{lstlisting} +#+end_latex + +* Code Snippet +#+begin_src python + a = raw_input("Enter a number") + try: + num = int(a) + except: + print "Wrong input ..." + +#+end_src + +* Using idb +#+begin_latex +\small +\begin{lstlisting} +In []: import mymodule +In []: mymodule.test() +--------------------------------------------- +NameError Traceback (most recent call last) + in () +mymodule.py in test() + 1 def test(): + 2 total=1+1 +----> 3 print spam +NameError: global name 'spam' is not defined + +In []: %debug +> mymodule.py(2)test() + 0 print spam +ipdb> total +2 +\end{lstlisting} + +#+end_latex + + + +* Summary + - Create simple tests for a function. + - Learn to Automate tests using many predefined test cases. + - Good coding standards. + - Difference between syntax error and exception. + - Handling exception using try and except. + - Using %debug for debugging on ipython. + +* 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 88a01948450d -r d33698326409 testing_and_debugging/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/testing_and_debugging/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,278 @@ +% Created 2010-11-12 Fri 02:00 +\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{verbatim} +def gcd(a, b): + if a % b == 0: + return b + return gcd(b, a%b) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Test for gcd.py} +\label{sec-3} + +\begin{itemize} +\item Edit gcd.py file +\end{itemize} + +\begin{verbatim} +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{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Automating tests} +\label{sec-4} + +\begin{verbatim} +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{verbatim} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-5} + + For the same inputs as gcd write automated tests for LCM. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-6} + +\begin{verbatim} +def gcd(a, b): + if a % b == 0: + return b + return gcd(b, a%b) + + def lcm(a, b): + return (a * b) / gcd(a, b) + + if __name__ == '__main__': + for line in open('lcmtestcases.txt'): + numbers = line.split() + x = int(numbers[0]) + y = int(numbers[1]) + result = int(numbers[2]) + if lcm(x, y) != result: + print "Failed lcm test for", x, y +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Meaning full names} +\label{sec-7} + +\begin{verbatim} + +amount = 12.68 +denom = 0.05 +nCoins = round(amount / denom) +rAmount = nCoins * denom +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Code style} +\label{sec-8} + +\begin{itemize} +\item Four Space Indentation +\item 79 character limit on a line +\item Funtions should be seperated by + blank line +\item Use Docstring +\item White space around operators + +\begin{itemize} +\item l = 32 \% 4 +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-9} + +\begin{itemize} +\item Give meaningful names to the variables in following + code + +\begin{itemize} +\item c = a / b +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-10} + +\begin{verbatim} + +quotient = dividend / divisor +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Code Snippet} +\label{sec-11} + +\begin{verbatim} + +while True print 'Hello world' +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Error} +\label{sec-12} + +\begin{lstlisting} + while True print 'Hello world' + \end{lstlisting} + \begin{lstlisting} + File "", line 1, in ? + while True print 'Hello world' +SyntaxError: invalid syntax +\end{lstlisting} +\end{frame} +\begin{frame}[fragile] +\frametitle{Code Snippet} +\label{sec-13} + +\begin{verbatim} +a = raw_input("Enter a number") +try: + num = int(a) + except: + print "Wrong input ..." +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Using idb} +\label{sec-14} + +\small +\begin{lstlisting} +In []: import mymodule +In []: mymodule.test() +--------------------------------------------- +NameError Traceback (most recent call last) + in () +mymodule.py in test() + 1 def test(): + 2 total=1+1 +----> 3 print spam +NameError: global name 'spam' is not defined + +In []: %debug +> mymodule.py(2)test() + 0 print spam +ipdb> total +2 +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-15} + +\begin{itemize} +\item Create simple tests for a function. +\item Learn to Automate tests using many predefined test cases. +\item Good coding standards. +\item Difference between syntax error and exception. +\item Handling exception using try and except. +\item Using \%debug for debugging on ipython. +\end{itemize} +\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 88a01948450d -r d33698326409 using python modules/four_plot.png Binary file using python modules/four_plot.png has changed diff -r 88a01948450d -r d33698326409 using python modules/four_plot.py --- a/using python modules/four_plot.py Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,11 +0,0 @@ -x=linspace(-5*pi, 5*pi, 500) -plot(x, x, 'b') -plot(x, -x, 'b') -plot(x, sin(x), 'g', linewidth=2) -plot(x, x*sin(x), 'r', linewidth=3) -legend(['x', '-x', 'sin(x)', 'xsin(x)']) -annotate('origin', xy = (0, 0)) -title('Four Plot') -xlim(-5*pi, 5*pi) -ylim(-5*pi, 5*pi) -#show() diff -r 88a01948450d -r d33698326409 using python modules/questions.rst --- a/using python modules/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,120 +0,0 @@ -Objective Questions -------------------- - -.. A mininum of 8 questions here (along with answers) - -1. What will be output of the following code snippet, - :: - - from math import sqrt - - def sqrt(i): - return i - - print sqrt(49) - - a. 7.0 - #. 7 - #. 49 - #. 49.0 - #. Error - -Answer: 49 - -2. What will be the output of the following code snippet, - :: - - import math - - def sqrt(i): - x = math.sqrt(i) - if int(x) == x: - return int(x) - else: - return x - - print math.sqrt(50), sqrt(50), math.sqrt(49), sqrt(49) - - a. 7.0710678118654755 7 7 7 - #. 7.0710678118654755 7 7.0 7 - #. 7 7 7 7 - #. 7.0710678118654755 7.0710678118654755 7.0 7 - -Answer: 7.0710678118654755, 7.0710678118654755, 7.0, 7 - -3. ``from math import *`` and ``import math`` does the same, - - a. True - #. False - -Answer: False - -4. Which among these libraries is part of python standard library, - - a. Mayavi - #. scipy - #. matplotlib - #. urllib2 - -Answer: urllib2 - -5. ``pylab.plot(x,sin(x))`` can be used in a script with ``from pylab - import *`` - - a. True - #. False - -Answer: False - -6. Which among this is correct, - - a. from scipy import plot - #. from numpy import plot - #. from matplotlib import plot - #. from pylab import plot - #. None of the above - -Answer: from pylab import plot - -7. Functions ``xlim()`` and ``ylim()`` can be imported to the current - name-space as, - - a. from pylab import xlim, ylim - #. import pylab - #. from scipy import xlim, ylim - #. import scipy - -Answer: from pylab import xlim, ylim - -8. ``scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500)`` - - a. creates an array of 500 equally spaced elements from -5*scipy.pi - to 5*scipy.pi(excluded) - #. creates an array of 500 equally spaced elements from - -5*scipy.pi(excluded) to 5*scipy.pi(included) - #. creates an array of 500 equally spaced elements from -5*scipy.pi - to 5*scipy.pi, both end points included - #. created an array of 500 equally spaced elements from -5*scipy.pi - to 5*scipy.pi, both end points excluded. - #. None of the above - -Answer: creates an array of 500 equally spaced elements from - -5*scipy.pi to 5*scipy.pi, both end points included - - -Larger Questions ----------------- - -.. A minimum of 2 questions here (along with answers) - -1. Write a python script to plot a red colour tan plot between -pi to - pi, with x limits from -pi to pi. Label the figure appropriately - and with a legend 'tan(x)' and title 'tangent plot'. Label the axes - x as 'x' and y as 'tan(x)'. Make sure the script can be executed as - a python script. - -2. Write a python script to plot a parabola of the form y^2=4ax with a - = 0.5(a is the directrix), plot the line in green color add the - legend as 'y^2=4ax' and title as 'parabola'. For x from -20 to 20 - with 100 equidistant points. Make sure the script can be executed - as a python script. [`Hint`: Use parametric equations] diff -r 88a01948450d -r d33698326409 using python modules/quickref.tex --- a/using python modules/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,16 +0,0 @@ -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 88a01948450d -r d33698326409 using python modules/script.rst --- a/using python modules/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,247 +0,0 @@ -.. Objectives -.. ---------- - -.. At the end of this tutorial, you will be able to - -.. 1. Execute python scripts from command line. -.. #. Use import in scripts. -.. #. Import scipy and pylab modules -.. #. Use python standard modules and 3rd party modules. - - -.. Prerequisites -.. ------------- - -.. 1. should have ``pylab`` installed. -.. #. using plot command interactively. -.. #. embellishing a plot. -.. #. saving plots. - -.. Author : Anoop Jacob Thomas - Internal Reviewer : Puneeth - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <11-11-2010, Anand, OK> [2010-10-05] - - -==================== -Using Python modules -==================== -{{{ show the welcome slide }}} - -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. 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 }}} - -Let us create a simple python script to print hello world. Open your -text editor and type the following, - -{{{ open the text editor and type the following }}} -:: - - print "Hello world!" - print - -and save the script as ``hello.py``, - -{{{ save the script as hello.py }}} - -Till now we saw how to run a script using the IPython interpreter -using the -:: - - %run -i hello.py - -option, but that is not the correct way of running a python -script. - -The correct method is to run it using the Python interpreter. Open the -terminal and navigate to the directory where hello.py is, - -{{{ open terminal and navigate to directory where hello.py was saved }}} - -{{{ switch to next slide }}} - -now run the Python script as, -:: - - python hello.py - -It executed the script and we got the output ``Hello World!``. - -{{{ highlight ``python filename`` syntax on slide while narrating }}} - -The syntax is python space filename. - -{{{ switch to next slide, four plot problem }}} - -Now recall the four plot problem where we plotted four plots in a single -figure. Let us run that script from command line. - -If you don't have the script, - -{{{ open the four_plot.py file in text editor }}} - -just pause here and create a python script with the following lines -and save it as four_plot.py. - -Now let us run four_plot.py as a python script. -:: - - python four_plot.py - -Oops! even though it was supposed to work, it didn't. It gave an error -``linspace()`` is not defined, which means that the function -``linspace()`` is not available in the current name-space. - -But if you try to run the same script using ``%run -i four_plot.py`` -in your IPython interpreter started with the option ``-pylab`` it will -work, because the ``-pylab`` option does some work for us by importing -the required modules to our name-space when ipython interpreter -starts. And thus we don't have to explicitly import modules. - -So now let us try to fix the problem and run the script in command -line, - -{{{ switch to next slide, fix ``linspace`` problem }}} - -add the following line as the first line in the script, -{{{ add the line as first line in four_plot.py and save }}} -:: - - from scipy import * - -Now let us run the script again, -:: - - python four_plot.py - -Now it gave another error -- plot not defined, let us edit the file -again and add the line below the line we just added, - -{{{ switch to next slide, fix ``plot`` problem }}} - -{{{ add the line as second line in four_plot.py and save }}} -:: - - from pylab import * - -And run the script, -:: - - python four_plot.py - -Yes! it worked. So what did we do? - -We actually imported the required modules using the keyword ``import``. -It could have also be done as, - -{{{ switch to next slide, better way of fixing }}} - -{{{ highlight the following in slide and say it loud }}} -:: - - from scipy import linspace - -instead of, -:: - - from scipy import * - -So in practice it is always good to use function names instead of -asterisk or star. If we use asterisk to import from a particular -module then it will replace any existing functions with the same name -in our name-space. - -{{{ switch to next slide, Instead of ``*`` }}} - -So let us modify four_plot.py as, -{{{ delete the first two lines and add the following }}} -:: - - from scipy import linspace, pi, sin - from pylab import plot, legend, annotate - from pylab import xlim, ylim, title, show - -Now let us try running the code again as, -:: - - python four_plot.py - -It works! In this method we actually imported the functions to the -current name-space, and there is another method of doing it. And that -is, - -{{{ switch to next slide }}} - -Notice that we use ``scipy.pi`` instead of just ``pi`` as in the -previous method, and the functions are called as ``pylab.plot()`` and -``pylab.annotate()`` and not as ``plot()`` and ``annotate()``. - -{{{ switch to next slide, problem statement }}} - -%% %% 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. - -It can solved as, - -{{{ open sine.py and show it }}} - -the first line we import the required functions ``linspace()`` and -``sin()`` and constant ``pi`` from the module scipy. the second and -third line we import the functions ``plot()``, ``legend()``, -``show()``, ``title()``, ``xlabel()`` and ``ylabel()``. And the rest -the code to generate the plot. - -We can run it as, -{{{ now switch focus to terminal and run the script }}} -:: - - python sine.py - -{{{ switch to next slide, What is a module? }}} - -Until now we have been learning about importing modules, now what is a -module? - -A module is simply a file containing Python definitions and -statements. Definitions from a module can be imported into other -modules or into the main module. - -{{{ switch to next slide, Python standard library }}} - -Python has a very rich standard library of modules. It is very -extensive, offering a wide range of facilities. Some of the standard -modules are, - -for Math: math, random -for Internet access: urllib2, smtplib -for System, Command line arguments: sys -for Operating system interface: os -for regular expressions: re -for compression: gzip, zipfile, tarfile -And there are lot more. - -Find more information at Python Library reference, -``http://docs.python.org/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 }}} - -This brings us to the end of this tutorial, in this tutorial we -learned running scripts from command line, learned about modules, saw -the python standard library. - -{{{ switch to next slide, thank you slide }}} - -Thank you! diff -r 88a01948450d -r d33698326409 using python modules/sine.py --- a/using python modules/sine.py Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,11 +0,0 @@ -from scipy import linspace, pi, sin -from pylab import plot, legend, show, title -from pylab import xlabel, ylabel - -x = linspace(-2*pi,2*pi,100) -plot(x,sin(x)) -legend(['sin(x)']) -title('Sine plot') -xlabel('x') -ylabel('sin(x)') -show() diff -r 88a01948450d -r d33698326409 using python modules/slides.org --- a/using python modules/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,125 +0,0 @@ -#+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: Using python modules -#+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 - - Running python scripts from command line - - Importing python modules - - Importing scipy \& pylab modules - - About python standard library. -* Running Python script from command line - - Create a script, open text editor and type the following - : print "hello world!" - : print - - Save the script as ~hello.py~ -* Running Python script from command line (cont'd) - - Run the script - : $ python hello.py - /Syntax :/ *python filename* -* Four plot problem - #+begin_latex - \begin{center} - \includegraphics[scale=0.4]{four_plot} - \end{center} - #+end_latex -* Fix ~linspace()~ problem - : from scipy import * -* Fix ~plot()~ problem - : from pylab import * -* Better way of fixing - : from scipy import linspace - instead of - : from scipy import * - ~*~ means import all functions from name-space ~scipy~. -* Instead of ~*~ - : from scipy import linspace, pi, sin - : from pylab import plot, legend, annotate - : from pylab import xlim, ylim, title, show - Is better than, ~from scipy import *~ \& ~from pylab import *~. -* Another Fix - #+begin_src python - import scipy - import pylab - x = scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500) - pylab.plot(x, x, 'b') - pylab.plot(x, -x, 'b') - pylab.plot(x, scipy.sin(x), 'g', linewidth=2) - pylab.plot(x, x*scipy.sin(x), 'r', linewidth=3) - pylab.legend(['x', '-x', 'sin(x)', 'xsin(x)']) - pylab.annotate('origin', xy = (0, 0)) - pylab.xlim(-5*scipy.pi, 5*scipy.pi) - pylab.ylim(-5*scipy.pi, 5*scipy.pi) - #+end_src -* Exercise 1 - Write a python script to plot a sine wave from - #+begin_latex - $-2\Pi$ - #+end_latex - to - #+begin_latex - $2\Pi$ - #+end_latex - . -* What is a module? - Module is simply a file containing Python definitions and - statements. Definitions from a module can be imported into other - modules or into the main module. -* Python standard library - Python has a very rich standard library of modules. - - Few libraries - - Math: ~math~, ~random~ - - Internet access: ~urllib2~, ~smtplib~ - - System, Command line arguments: ~sys~ - - Operating system interface: ~os~ - - regular expressions: ~re~ - - compression: ~gzip~, ~zipfile~, ~tarfile~ - - More information - - [[http://docs.python.org/library]] -* Summary - - Running scripts from command line - - Learned about modules - - importing modules - - Python standard library -* 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 88a01948450d -r d33698326409 using python modules/slides.tex --- a/using python modules/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,227 +0,0 @@ -% Created 2010-10-12 Tue 17:12 -\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{Using python modules} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Running python scripts from command line -\item Importing python modules -\item Importing scipy \& pylab modules -\item About python standard library. -\end{itemize} -\end{frame} -\begin{frame}[fragile] -\frametitle{Running Python script from command line} -\label{sec-2} - -\begin{itemize} -\item Create a script, open text editor and type the following -\begin{verbatim} - print "hello world!" - print -\end{verbatim} - -\item Save the script as \texttt{hello.py} -\end{itemize} -\end{frame} -\begin{frame}[fragile] -\frametitle{Running Python script from command line (cont'd)} -\label{sec-3} - -\begin{itemize} -\item Run the script -\begin{verbatim} - $ python hello.py -\end{verbatim} - -\end{itemize} - - \emph{Syntax :} \textbf{python filename} -\end{frame} -\begin{frame} -\frametitle{Four plot problem} -\label{sec-4} - - \begin{center} - \includegraphics[scale=0.4]{four_plot} - \end{center} -\end{frame} -\begin{frame}[fragile] -\frametitle{Fix \texttt{linspace()} problem} -\label{sec-5} - -\begin{verbatim} - from scipy import * -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Fix \texttt{plot()} problem} -\label{sec-6} - -\begin{verbatim} - from pylab import * -\end{verbatim} -\end{frame} -\begin{frame}[fragile] -\frametitle{Better way of fixing} -\label{sec-7} - -\begin{verbatim} - from scipy import linspace -\end{verbatim} - - instead of -\begin{verbatim} - from scipy import * -\end{verbatim} - - \texttt{*} means import all functions from name-space \texttt{scipy}. -\end{frame} -\begin{frame}[fragile] -\frametitle{Instead of \texttt{*}} -\label{sec-8} - -\begin{verbatim} - from scipy import linspace, pi, sin - from pylab import plot, legend, annotate - from pylab import xlim, ylim, title, show -\end{verbatim} - - Is better than, \texttt{from scipy import *} \& \texttt{from pylab import *}. -\end{frame} -\begin{frame}[fragile] -\frametitle{Another Fix} -\label{sec-9} - -\begin{verbatim} -import scipy -import pylab -x = scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500) -pylab.plot(x, x, 'b') -pylab.plot(x, -x, 'b') -pylab.plot(x, scipy.sin(x), 'g', linewidth=2) -pylab.plot(x, x*scipy.sin(x), 'r', linewidth=3) -pylab.legend(['x', '-x', 'sin(x)', 'xsin(x)']) -pylab.annotate('origin', xy = (0, 0)) -pylab.xlim(-5*scipy.pi, 5*scipy.pi) -pylab.ylim(-5*scipy.pi, 5*scipy.pi) -\end{verbatim} -\end{frame} -\begin{frame} -\frametitle{Exercise 1} -\label{sec-10} - - Write a python script to plot a sine wave from - $-2\Pi$ - to - $2\Pi$ - . -\end{frame} -\begin{frame} -\frametitle{What is a module?} -\label{sec-11} - - Module is simply a file containing Python definitions and - statements. Definitions from a module can be imported into other - modules or into the main module. -\end{frame} -\begin{frame} -\frametitle{Python standard library} -\label{sec-12} - - Python has a very rich standard library of modules. -\begin{itemize} -\item Few libraries - -\begin{itemize} -\item Math: \texttt{math}, \texttt{random} -\item Internet access: \texttt{urllib2}, \texttt{smtplib} -\item System, Command line arguments: \texttt{sys} -\item Operating system interface: \texttt{os} -\item regular expressions: \texttt{re} -\item compression: \texttt{gzip}, \texttt{zipfile}, \texttt{tarfile} -\end{itemize} - -\item More information - -\begin{itemize} -\item \href{http://docs.python.org/library}{http://docs.python.org/library} -\end{itemize} - -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-13} - -\begin{itemize} -\item Running scripts from command line -\item Learned about modules - -\begin{itemize} -\item importing modules -\end{itemize} - -\item Python standard library -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-14} - - \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 88a01948450d -r d33698326409 using-plot-interactively/buttons.png Binary file using-plot-interactively/buttons.png has changed diff -r 88a01948450d -r d33698326409 using-plot-interactively/home.png Binary file using-plot-interactively/home.png has changed diff -r 88a01948450d -r d33698326409 using-plot-interactively/move.png Binary file using-plot-interactively/move.png has changed diff -r 88a01948450d -r d33698326409 using-plot-interactively/questions.rst --- a/using-plot-interactively/questions.rst Wed Nov 17 23:24:57 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 88a01948450d -r d33698326409 using-plot-interactively/quickref.tex --- a/using-plot-interactively/quickref.tex Wed Nov 17 23:24:57 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 88a01948450d -r d33698326409 using-plot-interactively/save.png Binary file using-plot-interactively/save.png has changed diff -r 88a01948450d -r d33698326409 using-plot-interactively/script.rst --- a/using-plot-interactively/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,226 +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 -------- -{{{ Show the Title Slide }}} - -Hello and welcome to the tutorial on creating simple plots using -Python.This tutorial is presented by the Fossee group. - -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 :: - - 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. :: - - 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 :: - - - 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 :: - - p = linspace(-pi,pi,100) - - -'pi' here is constant defined by pylab. Save this to the variable, p -. - -If you now :: - - 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:: - - 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.:: - - cosine=cos(points) - - plot(p,cosine) - - - -Now do :: - - 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. :: - - - 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. - - - -{{{ Show how to save the file }}} - -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. - -{{{ Show how to zoom. Press zoom button and specify region to zoom }}} - -Left to this is zoom button to zoom into the plot. Just specify the -region to zoom into. - -{{{ Press Move button and move the axes. }}} - -The button left to it can be used to move the axes of the plot. - -{{{ Press Back and Forward Button }}} - -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. - -{{{ Press home button }}} - -The last one is 'home' referring to the initial plot. - - - - -Following is an exercise that you must do. - -%% %% Plot (sin(x)*sin(x))/x . - 1. Save the plot by the sinsquarebyx.pdf in pdf format. - 2. Zoom and find the maxima. - - 3. Bring it back to initial position. - - -Please, pause the video here. Do the exercise and then continue. - - - - - - - - - -{{{ 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 88a01948450d -r d33698326409 using-plot-interactively/slides.org --- a/using-plot-interactively/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,76 +0,0 @@ -#+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: Using Plot Interactively -#+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 - - Plot a simple mathemaical function. - - Using the User Interface of plot figure. - -* Error if Ipython not installed - -** `ERROR: matplotlib could NOT be imported! Starting normal IPython.` - - -* Plot UI -#+begin_latex - \includegraphics[height=0.12in, interpolate=true]{buttons} -#+end_latex - - Save - - Zoom - - Move axis - - Back and Forward Button - - Home - - -* Summary - - Plotting mathematical functions using plot. - - Using the UI of plot - - Save - - Zoom - - Move axis - - Back and Forward Button - - Home - -* 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 88a01948450d -r d33698326409 using-plot-interactively/slides.tex --- a/using-plot-interactively/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,99 +0,0 @@ -% Created 2010-11-11 Thu 13:15 -\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{Using Plot Interactively} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - - How to plot a simple mathematical function. - Using the User Interface of plot figure. -\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} - - \includegraphics[height=0.12in, interpolate=true]{buttons} -\begin{itemize} -\item Save -\item Zoom -\item Move axis -\item Back and Forward Button -\item Home -\end{itemize} - - - -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-4} - -\begin{itemize} -\item Plotting mathematical functions using plot. - \includegraphics[height=0.12in, interpolate=true]{buttons} -\item Using the UI of plot - -\begin{itemize} -\item Save -\item Zoom -\item Move axis -\item Back and Forward Button -\item Home -\end{itemize} - -\end{itemize} - - - -\end{frame} - -\end{document} diff -r 88a01948450d -r d33698326409 using-plot-interactively/zoom.png Binary file using-plot-interactively/zoom.png has changed diff -r 88a01948450d -r d33698326409 using-sage/questions.rst --- a/using-sage/questions.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,99 +0,0 @@ -Objective ---------- - -1. How do you find the limit of the function ``x/sin(x)`` as ``x`` tends to - ``0`` from the negative side. - - Answer: lim(x/sin(x), x=0, dir="below") - -#. Find the third differential of the function ``exp(sin(x)*cos(x^2))`` - - Answer: diff(exp(sin(x)*cos(x^2), x, 3) - -#. Solve the system of linear equations:: - - x-2y+3z = 7 - 2x+3y-z = 5 - x+2y+4z = 9 - - Answer:: - - A = Matrix([[1, -2, 3], - [2, 3, -1], - [1, 2, 4]]) - - b = vector([7, 5, 9]) - - solve_right(A, b) - -#. How do you get the factorized form of ``x^4 - 4x^2 + x^3 + 2x + 7`` - - Answer:: - - factor( x^4 + x^3 - 4*x^2 + 2*x + 7 ) - -#. list all the primes between 2009 and 2900 - - Answer: prime_range(2009, 2901) - -#. Which function is used to check primality - - a. isPrime - #. isprime - #. is_prime - #. prime - - Answer: is_prime - -#. How do you list all the combinations of ``[1, 2, 3, 4]`` - - - Answer:: - - c1 = Combinations([1, 2, 3, 4]) - c1.list() - -#. How do you list all the permutations of ``[1, 3, 2, 3]`` - - Answer:: - - p1 = Permutations([1, 3, 2, 3]) - p2.list() - - -Programming ------------ - -1. Obtain the sum of primes between 1 million and 2 million. - - Answer:: - - prime_sum = 0 - for i in range(1000001, 2000000, 2): - if is_prime(i): - prime_sum += i - - prime_sum - - OR - :: - - sum(prime_range(1000000, 2000000)) - -2. ``graphs.WorldMap()`` gives the world map in the form of a - graph. :: - - G = graphs.WorldMap() - G.vertices() - - - 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:: - - G.distance("India", "France") - - - - diff -r 88a01948450d -r d33698326409 using-sage/quickref.tex --- a/using-sage/quickref.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,8 +0,0 @@ -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 88a01948450d -r d33698326409 using-sage/script.rst --- a/using-sage/script.rst Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,224 +0,0 @@ -.. Objectives -.. ---------- - -.. By the end of this tutorial you will -- - -.. 1. Get an idea of the range of things for which Sage can be used. -.. #. Know some of the functions for Calculus -.. #. Get some insight into Graphs in Sage. - - -.. Prerequisites -.. ------------- - -.. Getting Started -- Sage - -.. Author : Puneeth - Internal Reviewer : Anoop Jacob Thomas - External Reviewer : - Language Reviewer : Bhanukiran - Checklist OK? : <06-11-2010, Anand, OK> [2010-10-05] - -Script ------- - -{{{ show the welcome slide }}} - -Hello Friends. Welcome to this tutorial on using Sage. - -{{{ show the slide with outline }}} - -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 }}} - -Let us begin with Calculus. We shall be looking at limits, -differentiation, integration, and Taylor polynomial. - -{{{ show sage notebook }}} - -We have our Sage notebook running. In case, you don't have it running, -start is using the command, ``sage --notebook``. - -To find the limit of the function x*sin(1/x), at x=0, we say -:: - - lim(x*sin(1/x), x=0) - -We get the limit to be 0, as expected. - -It is also possible to the limit at a point from one direction. For -example, let us find the limit of 1/x at x=0, when approaching from -the positive side. -:: - - lim(1/x, x=0, dir='above') - -To find the limit from the negative side, we say, -:: - - 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 -shall first define the expression, and then use the ``diff`` function -to obtain the differential of the expression. -:: - - var('x') - f = exp(sin(x^2))/x - - diff(f, x) - -We can also obtain the partial differentiation of an expression w.r.t -one of the variables. Let us differentiate the expression -``exp(sin(y - x^2))/x`` w.r.t x and y. -:: - - var('x y') - f = exp(sin(y - x^2))/x - - diff(f, x) - - diff(f, y) - -Now, let us look at integration. We shall use the expression obtained -from the differentiation that we did before, ``diff(f, y)`` --- -``e^(sin(-x^2 + y))*cos(-x^2 + y)/x``. The ``integrate`` command is -used to obtain the integral of an expression or function. -:: - - integrate(e^(sin(-x^2 + y))*cos(-x^2 + y)/x, y) - -We get back the correct expression. The minus sign being inside or -outside the ``sin`` function doesn't change much. - -Now, let us find the value of the integral between the limits 0 and -pi/2. -:: - - integral(e^(sin(-x^2 + y))*cos(-x^2 + y)/x, y, 0, pi/2) - -Let us now see how to obtain the Taylor expansion of an expression -using sage. Let us obtain the Taylor expansion of ``(x + 1)^n`` up to -degree 4 about 0. -:: - - var('x n') - taylor((x+1)^n, x, 0, 4) - -This brings us to the end of the features of Sage for Calculus, that -we will be looking at. For more, look at the Calculus quick-ref from -the Sage Wiki. - -Next let us move on to Matrix Algebra. - -{{{ show the equation on the slides }}} - -Let us begin with solving the equation ``Ax = v``, where A is the -matrix ``matrix([[1,2],[3,4]])`` and v is the vector -``vector([1,2])``. - -To solve the equation, ``Ax = v`` we simply say -:: - - x = solve_right(A, v) - -To solve the equation, ``xA = v`` we simply say -:: - - x = solve_left(A, v) - -The left and right here, denote the position of ``A``, relative to x. - -#[Puneeth]: any suggestions on what more to add? - -Now, let us look at Graph Theory in Sage. - -We shall look at some ways to create graphs and some of the graph -families available in Sage. - -The simplest way to define an arbitrary graph is to use a dictionary -of lists. We create a simple graph by -:: - - G = Graph({0:[1,2,3], 2:[4]}) - -We say -:: - - G.show() - -to view the visualization of the graph. - -Similarly, we can obtain a directed graph using the ``DiGraph`` -function. -:: - - G = DiGraph({0:[1,2,3], 2:[4]}) - - -Sage also provides a lot of graph families which can be viewed by -typing ``graph.``. Let us obtain a complete graph with 5 vertices -and then show the graph. -:: - - G = graphs.CompleteGraph(5) - - G.show() - - -Sage provides other functions for Number theory and -Combinatorics. Let's have a glimpse of a few of them. - - -:: - - prime_range(100, 200) - -gives primes in the range 100 to 200. - -:: - - is_prime(1999) - -checks if 1999 is a prime number or not. - -:: - - factor(2001) - -gives the factorized form of 2001. - -:: - - C = Permutations([1, 2, 3, 4]) - C.list() - -gives the permutations of ``[1, 2, 3, 4]`` - -:: - - C = Combinations([1, 2, 3, 4]) - C.list() - -gives all the combinations of ``[1, 2, 3, 4]`` - -That brings us to the end of this session showing various features -available in Sage. - -.. #[[Anoop: I feel we should add more slides, a possibility is to add - the code which they are required to type in, I also feel we should - add some review problems for them to try out.]] - -{{{ Show summary slide }}} - -We have looked at some of the functions available for Linear Algebra, -Calculus, Graph Theory and Number theory. - -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 88a01948450d -r d33698326409 using-sage/slides.org --- a/using-sage/slides.org Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,60 +0,0 @@ -#+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: using Sage -#+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 - - Calculus - - Linear Algebra - - Graph Theory - - Number Theory -* Summary - - Differentiating and Integrating - - Taylor Expansions - - Solving Equations - - Initializing Graphs & Graph families - - Prime numbers - - Factors - - Combinations & Permutations -* 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 88a01948450d -r d33698326409 using-sage/slides.tex --- a/using-sage/slides.tex Wed Nov 17 23:24:57 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,86 +0,0 @@ -% Created 2010-10-27 Wed 13:16 -\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{using Sage} -\author{FOSSEE} -\date{} - -\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} -\begin{document} - -\maketitle - - - - - - - - - -\begin{frame} -\frametitle{Outline} -\label{sec-1} - -\begin{itemize} -\item Calculus -\item Linear Algebra -\item Graph Theory -\item Number Theory -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Summary} -\label{sec-2} - -\begin{itemize} -\item Differentiating and Integrating -\item Taylor Expansions -\item Solving Equations -\item Initializing Graphs \& Graph families -\item Prime numbers -\item Factors -\item Combinations \& Permutations -\end{itemize} -\end{frame} -\begin{frame} -\frametitle{Thank you!} -\label{sec-3} - - \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 88a01948450d -r d33698326409 using_plot_interactively/buttons.png Binary file using_plot_interactively/buttons.png has changed diff -r 88a01948450d -r d33698326409 using_plot_interactively/home.png Binary file using_plot_interactively/home.png has changed diff -r 88a01948450d -r d33698326409 using_plot_interactively/move.png Binary file using_plot_interactively/move.png has changed diff -r 88a01948450d -r d33698326409 using_plot_interactively/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_plot_interactively/questions.rst Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 using_plot_interactively/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_plot_interactively/quickref.tex Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 using_plot_interactively/save.png Binary file using_plot_interactively/save.png has changed diff -r 88a01948450d -r d33698326409 using_plot_interactively/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_plot_interactively/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,226 @@ +.. 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 +------- +{{{ Show the Title Slide }}} + +Hello and welcome to the tutorial on creating simple plots using +Python.This tutorial is presented by the Fossee group. + +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 :: + + 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. :: + + 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 :: + + + 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 :: + + p = linspace(-pi,pi,100) + + +'pi' here is constant defined by pylab. Save this to the variable, p +. + +If you now :: + + 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:: + + 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.:: + + cosine=cos(points) + + plot(p,cosine) + + + +Now do :: + + 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. :: + + + 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. + + + +{{{ Show how to save the file }}} + +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. + +{{{ Show how to zoom. Press zoom button and specify region to zoom }}} + +Left to this is zoom button to zoom into the plot. Just specify the +region to zoom into. + +{{{ Press Move button and move the axes. }}} + +The button left to it can be used to move the axes of the plot. + +{{{ Press Back and Forward Button }}} + +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. + +{{{ Press home button }}} + +The last one is 'home' referring to the initial plot. + + + + +Following is an exercise that you must do. + +%% %% Plot (sin(x)*sin(x))/x . + 1. Save the plot by the sinsquarebyx.pdf in pdf format. + 2. Zoom and find the maxima. + + 3. Bring it back to initial position. + + +Please, pause the video here. Do the exercise and then continue. + + + + + + + + + +{{{ 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 88a01948450d -r d33698326409 using_plot_interactively/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_plot_interactively/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,76 @@ +#+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: Using Plot Interactively +#+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 + - Plot a simple mathemaical function. + - Using the User Interface of plot figure. + +* Error if Ipython not installed + +** `ERROR: matplotlib could NOT be imported! Starting normal IPython.` + + +* Plot UI +#+begin_latex + \includegraphics[height=0.12in, interpolate=true]{buttons} +#+end_latex + - Save + - Zoom + - Move axis + - Back and Forward Button + - Home + + +* Summary + - Plotting mathematical functions using plot. + - Using the UI of plot + - Save + - Zoom + - Move axis + - Back and Forward Button + - Home + +* 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 88a01948450d -r d33698326409 using_plot_interactively/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_plot_interactively/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,99 @@ +% Created 2010-11-11 Thu 13:15 +\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{Using Plot Interactively} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + + How to plot a simple mathematical function. + Using the User Interface of plot figure. +\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} + + \includegraphics[height=0.12in, interpolate=true]{buttons} +\begin{itemize} +\item Save +\item Zoom +\item Move axis +\item Back and Forward Button +\item Home +\end{itemize} + + + +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-4} + +\begin{itemize} +\item Plotting mathematical functions using plot. + \includegraphics[height=0.12in, interpolate=true]{buttons} +\item Using the UI of plot + +\begin{itemize} +\item Save +\item Zoom +\item Move axis +\item Back and Forward Button +\item Home +\end{itemize} + +\end{itemize} + + + +\end{frame} + +\end{document} diff -r 88a01948450d -r d33698326409 using_plot_interactively/zoom.png Binary file using_plot_interactively/zoom.png has changed diff -r 88a01948450d -r d33698326409 using_python_modules/four_plot.png Binary file using_python_modules/four_plot.png has changed diff -r 88a01948450d -r d33698326409 using_python_modules/four_plot.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_python_modules/four_plot.py Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,11 @@ +x=linspace(-5*pi, 5*pi, 500) +plot(x, x, 'b') +plot(x, -x, 'b') +plot(x, sin(x), 'g', linewidth=2) +plot(x, x*sin(x), 'r', linewidth=3) +legend(['x', '-x', 'sin(x)', 'xsin(x)']) +annotate('origin', xy = (0, 0)) +title('Four Plot') +xlim(-5*pi, 5*pi) +ylim(-5*pi, 5*pi) +#show() diff -r 88a01948450d -r d33698326409 using_python_modules/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_python_modules/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,120 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. What will be output of the following code snippet, + :: + + from math import sqrt + + def sqrt(i): + return i + + print sqrt(49) + + a. 7.0 + #. 7 + #. 49 + #. 49.0 + #. Error + +Answer: 49 + +2. What will be the output of the following code snippet, + :: + + import math + + def sqrt(i): + x = math.sqrt(i) + if int(x) == x: + return int(x) + else: + return x + + print math.sqrt(50), sqrt(50), math.sqrt(49), sqrt(49) + + a. 7.0710678118654755 7 7 7 + #. 7.0710678118654755 7 7.0 7 + #. 7 7 7 7 + #. 7.0710678118654755 7.0710678118654755 7.0 7 + +Answer: 7.0710678118654755, 7.0710678118654755, 7.0, 7 + +3. ``from math import *`` and ``import math`` does the same, + + a. True + #. False + +Answer: False + +4. Which among these libraries is part of python standard library, + + a. Mayavi + #. scipy + #. matplotlib + #. urllib2 + +Answer: urllib2 + +5. ``pylab.plot(x,sin(x))`` can be used in a script with ``from pylab + import *`` + + a. True + #. False + +Answer: False + +6. Which among this is correct, + + a. from scipy import plot + #. from numpy import plot + #. from matplotlib import plot + #. from pylab import plot + #. None of the above + +Answer: from pylab import plot + +7. Functions ``xlim()`` and ``ylim()`` can be imported to the current + name-space as, + + a. from pylab import xlim, ylim + #. import pylab + #. from scipy import xlim, ylim + #. import scipy + +Answer: from pylab import xlim, ylim + +8. ``scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500)`` + + a. creates an array of 500 equally spaced elements from -5*scipy.pi + to 5*scipy.pi(excluded) + #. creates an array of 500 equally spaced elements from + -5*scipy.pi(excluded) to 5*scipy.pi(included) + #. creates an array of 500 equally spaced elements from -5*scipy.pi + to 5*scipy.pi, both end points included + #. created an array of 500 equally spaced elements from -5*scipy.pi + to 5*scipy.pi, both end points excluded. + #. None of the above + +Answer: creates an array of 500 equally spaced elements from + -5*scipy.pi to 5*scipy.pi, both end points included + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Write a python script to plot a red colour tan plot between -pi to + pi, with x limits from -pi to pi. Label the figure appropriately + and with a legend 'tan(x)' and title 'tangent plot'. Label the axes + x as 'x' and y as 'tan(x)'. Make sure the script can be executed as + a python script. + +2. Write a python script to plot a parabola of the form y^2=4ax with a + = 0.5(a is the directrix), plot the line in green color add the + legend as 'y^2=4ax' and title as 'parabola'. For x from -20 to 20 + with 100 equidistant points. Make sure the script can be executed + as a python script. [`Hint`: Use parametric equations] diff -r 88a01948450d -r d33698326409 using_python_modules/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_python_modules/quickref.tex Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 using_python_modules/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_python_modules/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,247 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Execute python scripts from command line. +.. #. Use import in scripts. +.. #. Import scipy and pylab modules +.. #. Use python standard modules and 3rd party modules. + + +.. Prerequisites +.. ------------- + +.. 1. should have ``pylab`` installed. +.. #. using plot command interactively. +.. #. embellishing a plot. +.. #. saving plots. + +.. Author : Anoop Jacob Thomas + Internal Reviewer : Puneeth + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <11-11-2010, Anand, OK> [2010-10-05] + + +==================== +Using Python modules +==================== +{{{ show the welcome slide }}} + +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. 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 }}} + +Let us create a simple python script to print hello world. Open your +text editor and type the following, + +{{{ open the text editor and type the following }}} +:: + + print "Hello world!" + print + +and save the script as ``hello.py``, + +{{{ save the script as hello.py }}} + +Till now we saw how to run a script using the IPython interpreter +using the +:: + + %run -i hello.py + +option, but that is not the correct way of running a python +script. + +The correct method is to run it using the Python interpreter. Open the +terminal and navigate to the directory where hello.py is, + +{{{ open terminal and navigate to directory where hello.py was saved }}} + +{{{ switch to next slide }}} + +now run the Python script as, +:: + + python hello.py + +It executed the script and we got the output ``Hello World!``. + +{{{ highlight ``python filename`` syntax on slide while narrating }}} + +The syntax is python space filename. + +{{{ switch to next slide, four plot problem }}} + +Now recall the four plot problem where we plotted four plots in a single +figure. Let us run that script from command line. + +If you don't have the script, + +{{{ open the four_plot.py file in text editor }}} + +just pause here and create a python script with the following lines +and save it as four_plot.py. + +Now let us run four_plot.py as a python script. +:: + + python four_plot.py + +Oops! even though it was supposed to work, it didn't. It gave an error +``linspace()`` is not defined, which means that the function +``linspace()`` is not available in the current name-space. + +But if you try to run the same script using ``%run -i four_plot.py`` +in your IPython interpreter started with the option ``-pylab`` it will +work, because the ``-pylab`` option does some work for us by importing +the required modules to our name-space when ipython interpreter +starts. And thus we don't have to explicitly import modules. + +So now let us try to fix the problem and run the script in command +line, + +{{{ switch to next slide, fix ``linspace`` problem }}} + +add the following line as the first line in the script, +{{{ add the line as first line in four_plot.py and save }}} +:: + + from scipy import * + +Now let us run the script again, +:: + + python four_plot.py + +Now it gave another error -- plot not defined, let us edit the file +again and add the line below the line we just added, + +{{{ switch to next slide, fix ``plot`` problem }}} + +{{{ add the line as second line in four_plot.py and save }}} +:: + + from pylab import * + +And run the script, +:: + + python four_plot.py + +Yes! it worked. So what did we do? + +We actually imported the required modules using the keyword ``import``. +It could have also be done as, + +{{{ switch to next slide, better way of fixing }}} + +{{{ highlight the following in slide and say it loud }}} +:: + + from scipy import linspace + +instead of, +:: + + from scipy import * + +So in practice it is always good to use function names instead of +asterisk or star. If we use asterisk to import from a particular +module then it will replace any existing functions with the same name +in our name-space. + +{{{ switch to next slide, Instead of ``*`` }}} + +So let us modify four_plot.py as, +{{{ delete the first two lines and add the following }}} +:: + + from scipy import linspace, pi, sin + from pylab import plot, legend, annotate + from pylab import xlim, ylim, title, show + +Now let us try running the code again as, +:: + + python four_plot.py + +It works! In this method we actually imported the functions to the +current name-space, and there is another method of doing it. And that +is, + +{{{ switch to next slide }}} + +Notice that we use ``scipy.pi`` instead of just ``pi`` as in the +previous method, and the functions are called as ``pylab.plot()`` and +``pylab.annotate()`` and not as ``plot()`` and ``annotate()``. + +{{{ switch to next slide, problem statement }}} + +%% %% 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. + +It can solved as, + +{{{ open sine.py and show it }}} + +the first line we import the required functions ``linspace()`` and +``sin()`` and constant ``pi`` from the module scipy. the second and +third line we import the functions ``plot()``, ``legend()``, +``show()``, ``title()``, ``xlabel()`` and ``ylabel()``. And the rest +the code to generate the plot. + +We can run it as, +{{{ now switch focus to terminal and run the script }}} +:: + + python sine.py + +{{{ switch to next slide, What is a module? }}} + +Until now we have been learning about importing modules, now what is a +module? + +A module is simply a file containing Python definitions and +statements. Definitions from a module can be imported into other +modules or into the main module. + +{{{ switch to next slide, Python standard library }}} + +Python has a very rich standard library of modules. It is very +extensive, offering a wide range of facilities. Some of the standard +modules are, + +for Math: math, random +for Internet access: urllib2, smtplib +for System, Command line arguments: sys +for Operating system interface: os +for regular expressions: re +for compression: gzip, zipfile, tarfile +And there are lot more. + +Find more information at Python Library reference, +``http://docs.python.org/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 }}} + +This brings us to the end of this tutorial, in this tutorial we +learned running scripts from command line, learned about modules, saw +the python standard library. + +{{{ switch to next slide, thank you slide }}} + +Thank you! diff -r 88a01948450d -r d33698326409 using_python_modules/sine.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_python_modules/sine.py Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,11 @@ +from scipy import linspace, pi, sin +from pylab import plot, legend, show, title +from pylab import xlabel, ylabel + +x = linspace(-2*pi,2*pi,100) +plot(x,sin(x)) +legend(['sin(x)']) +title('Sine plot') +xlabel('x') +ylabel('sin(x)') +show() diff -r 88a01948450d -r d33698326409 using_python_modules/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_python_modules/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,125 @@ +#+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: Using python modules +#+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 + - Running python scripts from command line + - Importing python modules + - Importing scipy \& pylab modules + - About python standard library. +* Running Python script from command line + - Create a script, open text editor and type the following + : print "hello world!" + : print + - Save the script as ~hello.py~ +* Running Python script from command line (cont'd) + - Run the script + : $ python hello.py + /Syntax :/ *python filename* +* Four plot problem + #+begin_latex + \begin{center} + \includegraphics[scale=0.4]{four_plot} + \end{center} + #+end_latex +* Fix ~linspace()~ problem + : from scipy import * +* Fix ~plot()~ problem + : from pylab import * +* Better way of fixing + : from scipy import linspace + instead of + : from scipy import * + ~*~ means import all functions from name-space ~scipy~. +* Instead of ~*~ + : from scipy import linspace, pi, sin + : from pylab import plot, legend, annotate + : from pylab import xlim, ylim, title, show + Is better than, ~from scipy import *~ \& ~from pylab import *~. +* Another Fix + #+begin_src python + import scipy + import pylab + x = scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500) + pylab.plot(x, x, 'b') + pylab.plot(x, -x, 'b') + pylab.plot(x, scipy.sin(x), 'g', linewidth=2) + pylab.plot(x, x*scipy.sin(x), 'r', linewidth=3) + pylab.legend(['x', '-x', 'sin(x)', 'xsin(x)']) + pylab.annotate('origin', xy = (0, 0)) + pylab.xlim(-5*scipy.pi, 5*scipy.pi) + pylab.ylim(-5*scipy.pi, 5*scipy.pi) + #+end_src +* Exercise 1 + Write a python script to plot a sine wave from + #+begin_latex + $-2\Pi$ + #+end_latex + to + #+begin_latex + $2\Pi$ + #+end_latex + . +* What is a module? + Module is simply a file containing Python definitions and + statements. Definitions from a module can be imported into other + modules or into the main module. +* Python standard library + Python has a very rich standard library of modules. + - Few libraries + - Math: ~math~, ~random~ + - Internet access: ~urllib2~, ~smtplib~ + - System, Command line arguments: ~sys~ + - Operating system interface: ~os~ + - regular expressions: ~re~ + - compression: ~gzip~, ~zipfile~, ~tarfile~ + - More information + - [[http://docs.python.org/library]] +* Summary + - Running scripts from command line + - Learned about modules + - importing modules + - Python standard library +* 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 88a01948450d -r d33698326409 using_python_modules/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_python_modules/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,227 @@ +% Created 2010-10-12 Tue 17:12 +\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{Using python modules} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Running python scripts from command line +\item Importing python modules +\item Importing scipy \& pylab modules +\item About python standard library. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Running Python script from command line} +\label{sec-2} + +\begin{itemize} +\item Create a script, open text editor and type the following +\begin{verbatim} + print "hello world!" + print +\end{verbatim} + +\item Save the script as \texttt{hello.py} +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Running Python script from command line (cont'd)} +\label{sec-3} + +\begin{itemize} +\item Run the script +\begin{verbatim} + $ python hello.py +\end{verbatim} + +\end{itemize} + + \emph{Syntax :} \textbf{python filename} +\end{frame} +\begin{frame} +\frametitle{Four plot problem} +\label{sec-4} + + \begin{center} + \includegraphics[scale=0.4]{four_plot} + \end{center} +\end{frame} +\begin{frame}[fragile] +\frametitle{Fix \texttt{linspace()} problem} +\label{sec-5} + +\begin{verbatim} + from scipy import * +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Fix \texttt{plot()} problem} +\label{sec-6} + +\begin{verbatim} + from pylab import * +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Better way of fixing} +\label{sec-7} + +\begin{verbatim} + from scipy import linspace +\end{verbatim} + + instead of +\begin{verbatim} + from scipy import * +\end{verbatim} + + \texttt{*} means import all functions from name-space \texttt{scipy}. +\end{frame} +\begin{frame}[fragile] +\frametitle{Instead of \texttt{*}} +\label{sec-8} + +\begin{verbatim} + from scipy import linspace, pi, sin + from pylab import plot, legend, annotate + from pylab import xlim, ylim, title, show +\end{verbatim} + + Is better than, \texttt{from scipy import *} \& \texttt{from pylab import *}. +\end{frame} +\begin{frame}[fragile] +\frametitle{Another Fix} +\label{sec-9} + +\begin{verbatim} +import scipy +import pylab +x = scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500) +pylab.plot(x, x, 'b') +pylab.plot(x, -x, 'b') +pylab.plot(x, scipy.sin(x), 'g', linewidth=2) +pylab.plot(x, x*scipy.sin(x), 'r', linewidth=3) +pylab.legend(['x', '-x', 'sin(x)', 'xsin(x)']) +pylab.annotate('origin', xy = (0, 0)) +pylab.xlim(-5*scipy.pi, 5*scipy.pi) +pylab.ylim(-5*scipy.pi, 5*scipy.pi) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Exercise 1} +\label{sec-10} + + Write a python script to plot a sine wave from + $-2\Pi$ + to + $2\Pi$ + . +\end{frame} +\begin{frame} +\frametitle{What is a module?} +\label{sec-11} + + Module is simply a file containing Python definitions and + statements. Definitions from a module can be imported into other + modules or into the main module. +\end{frame} +\begin{frame} +\frametitle{Python standard library} +\label{sec-12} + + Python has a very rich standard library of modules. +\begin{itemize} +\item Few libraries + +\begin{itemize} +\item Math: \texttt{math}, \texttt{random} +\item Internet access: \texttt{urllib2}, \texttt{smtplib} +\item System, Command line arguments: \texttt{sys} +\item Operating system interface: \texttt{os} +\item regular expressions: \texttt{re} +\item compression: \texttt{gzip}, \texttt{zipfile}, \texttt{tarfile} +\end{itemize} + +\item More information + +\begin{itemize} +\item \href{http://docs.python.org/library}{http://docs.python.org/library} +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-13} + +\begin{itemize} +\item Running scripts from command line +\item Learned about modules + +\begin{itemize} +\item importing modules +\end{itemize} + +\item Python standard library +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-14} + + \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 88a01948450d -r d33698326409 using_sage/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_sage/questions.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,99 @@ +Objective +--------- + +1. How do you find the limit of the function ``x/sin(x)`` as ``x`` tends to + ``0`` from the negative side. + + Answer: lim(x/sin(x), x=0, dir="below") + +#. Find the third differential of the function ``exp(sin(x)*cos(x^2))`` + + Answer: diff(exp(sin(x)*cos(x^2), x, 3) + +#. Solve the system of linear equations:: + + x-2y+3z = 7 + 2x+3y-z = 5 + x+2y+4z = 9 + + Answer:: + + A = Matrix([[1, -2, 3], + [2, 3, -1], + [1, 2, 4]]) + + b = vector([7, 5, 9]) + + solve_right(A, b) + +#. How do you get the factorized form of ``x^4 - 4x^2 + x^3 + 2x + 7`` + + Answer:: + + factor( x^4 + x^3 - 4*x^2 + 2*x + 7 ) + +#. list all the primes between 2009 and 2900 + + Answer: prime_range(2009, 2901) + +#. Which function is used to check primality + + a. isPrime + #. isprime + #. is_prime + #. prime + + Answer: is_prime + +#. How do you list all the combinations of ``[1, 2, 3, 4]`` + + + Answer:: + + c1 = Combinations([1, 2, 3, 4]) + c1.list() + +#. How do you list all the permutations of ``[1, 3, 2, 3]`` + + Answer:: + + p1 = Permutations([1, 3, 2, 3]) + p2.list() + + +Programming +----------- + +1. Obtain the sum of primes between 1 million and 2 million. + + Answer:: + + prime_sum = 0 + for i in range(1000001, 2000000, 2): + if is_prime(i): + prime_sum += i + + prime_sum + + OR + :: + + sum(prime_range(1000000, 2000000)) + +2. ``graphs.WorldMap()`` gives the world map in the form of a + graph. :: + + G = graphs.WorldMap() + G.vertices() + + + 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:: + + G.distance("India", "France") + + + + diff -r 88a01948450d -r d33698326409 using_sage/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_sage/quickref.tex Wed Dec 01 16:51:35 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 88a01948450d -r d33698326409 using_sage/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_sage/script.rst Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,224 @@ +.. Objectives +.. ---------- + +.. By the end of this tutorial you will -- + +.. 1. Get an idea of the range of things for which Sage can be used. +.. #. Know some of the functions for Calculus +.. #. Get some insight into Graphs in Sage. + + +.. Prerequisites +.. ------------- + +.. Getting Started -- Sage + +.. Author : Puneeth + Internal Reviewer : Anoop Jacob Thomas + External Reviewer : + Language Reviewer : Bhanukiran + Checklist OK? : <06-11-2010, Anand, OK> [2010-10-05] + +Script +------ + +{{{ show the welcome slide }}} + +Hello Friends. Welcome to this tutorial on using Sage. + +{{{ show the slide with outline }}} + +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 }}} + +Let us begin with Calculus. We shall be looking at limits, +differentiation, integration, and Taylor polynomial. + +{{{ show sage notebook }}} + +We have our Sage notebook running. In case, you don't have it running, +start is using the command, ``sage --notebook``. + +To find the limit of the function x*sin(1/x), at x=0, we say +:: + + lim(x*sin(1/x), x=0) + +We get the limit to be 0, as expected. + +It is also possible to the limit at a point from one direction. For +example, let us find the limit of 1/x at x=0, when approaching from +the positive side. +:: + + lim(1/x, x=0, dir='above') + +To find the limit from the negative side, we say, +:: + + 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 +shall first define the expression, and then use the ``diff`` function +to obtain the differential of the expression. +:: + + var('x') + f = exp(sin(x^2))/x + + diff(f, x) + +We can also obtain the partial differentiation of an expression w.r.t +one of the variables. Let us differentiate the expression +``exp(sin(y - x^2))/x`` w.r.t x and y. +:: + + var('x y') + f = exp(sin(y - x^2))/x + + diff(f, x) + + diff(f, y) + +Now, let us look at integration. We shall use the expression obtained +from the differentiation that we did before, ``diff(f, y)`` --- +``e^(sin(-x^2 + y))*cos(-x^2 + y)/x``. The ``integrate`` command is +used to obtain the integral of an expression or function. +:: + + integrate(e^(sin(-x^2 + y))*cos(-x^2 + y)/x, y) + +We get back the correct expression. The minus sign being inside or +outside the ``sin`` function doesn't change much. + +Now, let us find the value of the integral between the limits 0 and +pi/2. +:: + + integral(e^(sin(-x^2 + y))*cos(-x^2 + y)/x, y, 0, pi/2) + +Let us now see how to obtain the Taylor expansion of an expression +using sage. Let us obtain the Taylor expansion of ``(x + 1)^n`` up to +degree 4 about 0. +:: + + var('x n') + taylor((x+1)^n, x, 0, 4) + +This brings us to the end of the features of Sage for Calculus, that +we will be looking at. For more, look at the Calculus quick-ref from +the Sage Wiki. + +Next let us move on to Matrix Algebra. + +{{{ show the equation on the slides }}} + +Let us begin with solving the equation ``Ax = v``, where A is the +matrix ``matrix([[1,2],[3,4]])`` and v is the vector +``vector([1,2])``. + +To solve the equation, ``Ax = v`` we simply say +:: + + x = solve_right(A, v) + +To solve the equation, ``xA = v`` we simply say +:: + + x = solve_left(A, v) + +The left and right here, denote the position of ``A``, relative to x. + +#[Puneeth]: any suggestions on what more to add? + +Now, let us look at Graph Theory in Sage. + +We shall look at some ways to create graphs and some of the graph +families available in Sage. + +The simplest way to define an arbitrary graph is to use a dictionary +of lists. We create a simple graph by +:: + + G = Graph({0:[1,2,3], 2:[4]}) + +We say +:: + + G.show() + +to view the visualization of the graph. + +Similarly, we can obtain a directed graph using the ``DiGraph`` +function. +:: + + G = DiGraph({0:[1,2,3], 2:[4]}) + + +Sage also provides a lot of graph families which can be viewed by +typing ``graph.``. Let us obtain a complete graph with 5 vertices +and then show the graph. +:: + + G = graphs.CompleteGraph(5) + + G.show() + + +Sage provides other functions for Number theory and +Combinatorics. Let's have a glimpse of a few of them. + + +:: + + prime_range(100, 200) + +gives primes in the range 100 to 200. + +:: + + is_prime(1999) + +checks if 1999 is a prime number or not. + +:: + + factor(2001) + +gives the factorized form of 2001. + +:: + + C = Permutations([1, 2, 3, 4]) + C.list() + +gives the permutations of ``[1, 2, 3, 4]`` + +:: + + C = Combinations([1, 2, 3, 4]) + C.list() + +gives all the combinations of ``[1, 2, 3, 4]`` + +That brings us to the end of this session showing various features +available in Sage. + +.. #[[Anoop: I feel we should add more slides, a possibility is to add + the code which they are required to type in, I also feel we should + add some review problems for them to try out.]] + +{{{ Show summary slide }}} + +We have looked at some of the functions available for Linear Algebra, +Calculus, Graph Theory and Number theory. + +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 88a01948450d -r d33698326409 using_sage/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_sage/slides.org Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,60 @@ +#+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: using Sage +#+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 + - Calculus + - Linear Algebra + - Graph Theory + - Number Theory +* Summary + - Differentiating and Integrating + - Taylor Expansions + - Solving Equations + - Initializing Graphs & Graph families + - Prime numbers + - Factors + - Combinations & Permutations +* 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 88a01948450d -r d33698326409 using_sage/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_sage/slides.tex Wed Dec 01 16:51:35 2010 +0530 @@ -0,0 +1,86 @@ +% Created 2010-10-27 Wed 13:16 +\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{using Sage} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Calculus +\item Linear Algebra +\item Graph Theory +\item Number Theory +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-2} + +\begin{itemize} +\item Differentiating and Integrating +\item Taylor Expansions +\item Solving Equations +\item Initializing Graphs \& Graph families +\item Prime numbers +\item Factors +\item Combinations \& Permutations +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-3} + + \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}