# HG changeset patch # User Nishanth # Date 1287416494 -19800 # Node ID c77f7f5850dd917288b5cd63daf608fba01bb7c4 # Parent c4cb18752adefedba4c1cc1dadaac869d0589a93# Parent d5248a15274cb67dc30d9f7f79f670572f09ea14 Merged diff -r d5248a15274c -r c77f7f5850dd basic-data-type/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic-data-type/questions.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,83 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. How large can an integer in Python be? + + Any Size. + + +2. How do you define a complex number in Python? + + Using the following notation. + + [Real part] + [Imaginary part] j + example :: + + c= 3.2 + 4.6j + + + +3. Look at the following piece of code :: + + In []: f or t + Out[]:True + + What can you comment about the data type of f and t ? + +4. One major diffence between tuples and lists? + + Tuples are immutable while lists are not. + + +5. 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. + + +6. Put the following string in a variable quotation. + "God doesn't play dice" -Albert Einstein + + quotation='''"God doesn't play dice" -Albert Einstein''' + +7. Given a tuple :: + + tup=(7,4,2,1,3,6,5,8) + tup[-2] + + 5 + +8. What is the syntax for checking containership in Python?:: + + element in sequence + 'l' in "Hello" + True + +9. Split this string on whitespaces? :: + + string="Split this string on whitespaces?" + + string.split() + +10. What is the answer of 5/2 and 5.0/2 . If yes , why. + + Yes, There is a difference. + Because one is integer division and other is float division. + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Given two lists for example, + list1=[1,2,3,4] and list2=[1,2,3,4,5,6,7] write a program to remove one list from the other. + + +#. Write a program to check if a string is palindrome? + diff -r d5248a15274c -r c77f7f5850dd basic-data-type/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic-data-type/quickref.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd basic-data-type/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic-data-type/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,467 @@ +.. Objectives +.. ---------- + +.. Learn about Python Data Structures and Operators.(Remembering) +.. Use them to do basic operations.(Applying) + +.. Prerequisites +.. ------------- + + + +.. 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 + * Operators in Python + +with a little hands-on on how they can be applied to the different data types. + + + +First we will explore python data structures in the domain of numbers. +There are three built-in data types in python to represent numbers. + +{{{ A slide to make a memory note of this }}} + +These are: + + * Integers + * float and + * Complex + +Lets first talk about integers. :: + + a = 13 + a + + +Thats it, there we have our first integer variable a. + + + +If we now see :: + + type(a) + + +This means that a is a type of int. Being an int data structure +in python means that there are various functions that this variable +has to manipulate it different ways. You can explore these by doing, + + a. + + + +Lets see the limits of this int. + + b = 99999999999999999999 + b + +As you can see even when we put a value of 9 repeated 20 times +python did not complain. However when you asked python to print +the number again it put a capital L at the end. Now if you check +the type of this variable b, :: + + type(b) + + + +The reason for this is that python recognizes large integer numbers +by the data type long. However long type and integer type share there +functions and properties. + +Lets now try out the second type in list called float. + +Decimal numbers in python are recognized by the term float :: + + p = 3.141592 + p + +If you notice the value of output of p isn't exactly equal to p. This +is because computer saves floating point values in a specific +format. There is always an aproximationation. This is why we should +never rely on equality of floating point numbers in a program. + +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. +Lets check 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) + + + +{{ Slide for memory aid }} + +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 explanotary in themselves. + +The usage of boolean brings us to an interesting question of precendence. +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. + + In[]: a=False + In[]: b=True + In[]: 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. + + +Lets now look at some operators available in Python to manipulate these data types. + + + +Python uses % 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 + + +Lets now discuss sequence data stypes in python. Sequence +datatypes are those in which elements are kept in a sequential +order. All the elements accessed using index. + + +{{{ slide to for memory aid }}} + +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 + + + +Now we will have a look at strings + +type :: + + In[]: greeting_string="hello" + + +greeting_string is now a string variable with the value "hello" + +{{{ Memory Aid Slide }}} + +Python strings can actually be defined in three different ways :: + + In[]: k='Single quote' + In[]: l="Double quote contain's single quote" + In[]: m='''"Contain's both"''' + +Thus, 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.:: + + In[]: 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 :: + + In[]: num_list[2] + In[]: num_list[-1] + In[]: greeting_string[1] + In[]: greeting_string[3] + In[]: greeting_string[-2] + In[]: num_tuple[2] + In[]: 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 :: + + In[]: num_list+var_list + In[]: a_string="another string" + In[]: greeting_string+a_string + In[]: t2=(3,4,6,7) + In[]: num_tuple+t2 + +len function gives the length :: + + In[]: len(num_list) + In[]: len(greeting_string) + In[]: len(num_tuple) + +Prints the length the variable. + +We can check the containership of an element using the 'in' keyword :: + + In[]: 3 in num_list + In[]: 'H' in greeting_string + In[]: 2 in num_tuple + +We see that it gives True and False accordingly. + +Find maximum using max function and minimum using min:: + + In[]: max(num_tuple) + In[]: min(greeting_string) + +Get a sorted list and reversed list using sorted and reversed function :: + + In[]: sorted(num_list) + In[]: reversed(greeting_string) + +As a consequence of the order one we access a group of elements together. +This is called slicing and striding. + +First Slicing + +Given a list :: + + In[]:j=[1,2,3,4,5,6] + +Lets say we want elements starting from 2 and ending in 5. + +For this we can do :: + + In[]: 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 notincluded in the resultant list:: + + + In[]: j[:4] + +If first element is left blank default is from beginning and if last +element is left blank it means till the end. + + In[]: j[1:] + + In[]: 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.:: + + In[]: new_num_list[1]=9 + In[]: 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 :: + + In[]: 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 string to list and list to string is an interesting problem. +Lets 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.:: + + In[]:','.join['List','joined','on','commas'] + +Thus we get a list joined on commas. Similarly we can do spaces.:: + + In[]:' '.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 . + +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. + + + + +.. #[Nishanth]: string to list is fine. But list to string can be left for + string manipulations. Just say it requires some string + manipulations and leave it there. + +.. #[Nishanth]: Where is the summary + There are no exercises in the script + +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. + +Thank You. + + + diff -r d5248a15274c -r c77f7f5850dd basic-data-type/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic-data-type/slides.org Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,72 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC +#+OPTIONS: H:5 num:t toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t + +#+TITLE: Plotting Data +#+AUTHOR: FOSSEE +#+DATE: 2010-09-14 Tue +#+EMAIL: info@fossee.in + +# \author[FOSSEE] {FOSSEE} + +# \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +# \date{} + +* Tutorial Plan +** Datatypes in Python +** Operators in Python + +* Numbers +** Integers +** Float +** Complex + +* Boolean +** True +** False + +* Sequence Data types +** Data in Sequence +** Accessed using Index +*** list +*** String +*** Tuple + +* All are Strings + +** k='Single quote' +** l="Double quote contain's single quote" +** m='''"Contain's both"''' + +* Summary +** a=73 +** b=3.14 +** c=3+4j + +* Summary Contd. + +** t=True +** f=False +** t and f + +* Summary Contd. +** l= [2,1,4,3] +** s='hello' +** tu=(1,2,3,4) + +* Summary Contd. +** tu[-1] +** s[1:-1] + +* Summary Contd. + +** Sorted(l) +** reversed(s) + + + diff -r d5248a15274c -r c77f7f5850dd basic-data-type/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/basic-data-type/slides.tex Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,158 @@ +% Created 2010-10-13 Wed 17:08 +\documentclass[presentation]{beamer} +\usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{amssymb} +\usepackage{hyperref} + + +\title{Plotting Data } +\author{FOSSEE} +\date{2010-09-14 Tue} + +\begin{document} + +\maketitle + + + + + + +\begin{frame} +\frametitle{Tutorial Plan} +\label{sec-1} +\begin{itemize} + +\item Datatypes in Python\\ +\label{sec-1.1}% +\item Operators in Python\\ +\label{sec-1.2}% +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Numbers} +\label{sec-2} +\begin{itemize} + +\item Integers\\ +\label{sec-2.1}% +\item Float\\ +\label{sec-2.2}% +\item Complex\\ +\label{sec-2.3}% +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Boolean} +\label{sec-3} +\begin{itemize} + +\item True\\ +\label{sec-3.1}% +\item False\\ +\label{sec-3.2}% +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Sequence Data types} +\label{sec-4} +\begin{itemize} + +\item Data in Sequence\\ +\label{sec-4.1}% +\item Accessed using Index +\label{sec-4.2}% +\begin{itemize} + +\item list\\ +\label{sec-4.2.1}% +\item String\\ +\label{sec-4.2.2}% +\item Tuple\\ +\label{sec-4.2.3}% +\end{itemize} % ends low level +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{All are Strings} +\label{sec-5} +\begin{itemize} + +\item k='Single quote'\\ +\label{sec-5.1}% +\item l="Double quote contain's single quote"\\ +\label{sec-5.2}% +\item m='''"Contain's both"'''\\ +\label{sec-5.3}% +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-6} +\begin{itemize} + +\item a=73\\ +\label{sec-6.1}% +\item b=3.14\\ +\label{sec-6.2}% +\item c=3+4j\\ +\label{sec-6.3}% +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Summary Contd.} +\label{sec-7} +\begin{itemize} + +\item t=True\\ +\label{sec-7.1}% +\item f=False\\ +\label{sec-7.2}% +\item t and f\\ +\label{sec-7.3}% +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Summary Contd.} +\label{sec-8} +\begin{itemize} + +\item l= [2,1,4,3]\\ +\label{sec-8.1}% +\item s='hello'\\ +\label{sec-8.2}% +\item tu=(1,2,3,4)\\ +\label{sec-8.3}% +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Summary Contd.} +\label{sec-9} +\begin{itemize} + +\item tu[-1]\\ +\label{sec-9.1}% +\item s[1:-1]\\ +\label{sec-9.2}% +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Summary Contd.} +\label{sec-10} +\begin{itemize} + +\item Sorted(l)\\ +\label{sec-10.1}% +\item reversed(s)\\ +\label{sec-10.2}% +\end{itemize} % ends low level +\end{frame} + +\end{document} diff -r d5248a15274c -r c77f7f5850dd basicdatatype.rst --- a/basicdatatype.rst Tue Oct 12 11:44:33 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,405 +0,0 @@ -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:: - - * Various Datatypes in Python - * Operators with a little hands-on on how they can be applied to - the different data types. - - - -First we will explore python data structures in the domain of numbers. -There are three built-in data types in python to represent numbers. - -{{{ A slide to make a memory note of this }}} - -These are: - - * Integers - * Complex and - * Boolean - -Lets first talk about integers. :: - - a = 13 - a - - -Thats it, there we have our first integer variable a. - - - -If we now see :: - - type(a) - - -This means that a is a type of int. Being an int data structure -in python means that there are various functions that this variable -has to manipulate it different ways. You can explore these by doing, - - a. - - - -Lets see the limits of this int. - - b = 99999999999999999999 - b - -As you can see even when we put a value of 9 repeated 20 times -python did not complain. However when you asked python to print -the number again it put a capital L at the end. Now if you check -the type of this variable b, :: - - type(b) - - - -The reason for this is that python recognizes large integer numbers -by the data type long. However long type and integer type share there -functions and properties. - -Lets now try out the second type in list called float. - -Decimal numbers in python are recognized by the term float :: - - p = 3.141592 - p - -If you notice the value of output of p isn't exactly equal to p. This -is because computer saves floating point values in a specific -format. There is always an aproximationation. This is why we should -never rely on equality of floating point numbers in a program. - -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 define by j notation instead of i. Complex numbers have a lot of functions specific to them. -Lets check 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) - -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 explanotary in themselves. - -The usage of boolean brings us to an interesting question of precendence. -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. - - In[]: a=False - In[]: b=True - In[]: 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. - -Lets now discuss sequence data structures in python. Sequence -datatypes are those in which elements are kept in a sequential -order. All the elements accessed using index. - -{{{ slide to for memory aid }}} - -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 - - - -Now we will have a look at strings - -type :: - - In[]: greeting_string="hello" - - -greeting_string is now a string variable with the value "hello" - -{{{ Memory Aid Slide }}} - -Python strings can actually be defined in three different ways :: - - In[]: k='Single quote' - In[]: l="Double quote contain's single quote" - In[]: m='''"Contain's both"''' - -Thus, 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.:: - - In[]: 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. - -{{{ Slide for memory aid }}} - -The first one is accessing. - -They can be accessed using index numbers :: - - In[]: num_list[2] - In[]: num_list[-1] - In[]: greeting_string[1] - In[]: greeting_string[3] - In[]: greeting_string[-2] - In[]: num_tuple[2] - In[]: 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 :: - - In[]: num_list+var_list - In[]: a_string="another string" - In[]: greeting_string+a_string - In[]: t2=(3,4,6,7) - In[]: num_tuple+t2 - -len function gives the length :: - - In[]: len(num_list) - In[]: len(greeting_string) - In[]: len(num_tuple) - -Prints the length the variable. - -We can check the containership of an element using the 'in' keyword :: - - In[]: 3 in num_list - In[]: 'H' in greeting_string - In[]: 2 in num_tuple - -We see that it gives True and False accordingly. - -Find maximum using max function and minimum using min:: - - In[]: max(num_tuple) - In[]: min(greeting_string) - -Get a sorted list and reversed list using sorted and reversed function :: - - In[]: sorted(num_list) - In[]: reversed(greeting_string) - -As a consequence of the order one we access a group of elements together. -This is called slicing and striding. - -First Slicing - -Given a list :: - - In[]:j=[1,2,3,4,5,6] - -Lets say we want elements starting from 2 and ending in 5. - -For this we can do :: - - In[]: 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 notincluded in the resultant list:: - - - In[]: j[:4] - -If first element is left blank default is from beginning and if last -element is left blank it means till the end. - - In[]: j[1:] - - In[]: 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.:: - - In[]: new_num_list[1]=9 - In[]: 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 :: - - In[]: 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 string to list and list to string is an interesting problem. -Lets 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.:: - - In[]:','.join['List','joined','on','commas'] - -Thus we get a list joined on commas. Similarly we can do spaces.:: - - In[]:' '.join['Now','on','spaces'] - -Note that the list has to be a list of strings to apply join operation. - -.. #[Nishanth]: string to list is fine. But list to string can be left for - string manipulations. Just say it requires some string - manipulations and leave it there. - -.. #[Nishanth]: Where is the summary - There are no exercises in the script - -{{{ Show the "sponsored by FOSSEE" slide }}} - -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. - -Thank You. - - - -Author : Amit Sethi -Internal Reviewer 1 : Nishanth -Internal Reviewer 2 : -External Reviewer diff -r d5248a15274c -r c77f7f5850dd conditionals.rst --- a/conditionals.rst Tue Oct 12 11:44:33 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,176 +0,0 @@ -Hello friends. Welcome to this spoken tutorial on Getting started with -strings. - -{{{ Show the slide containing the title }}} - -{{{ Show the slide containing the outline }}} - -In this tutorial, we will learn the basic conditional constructs -available in Python. We learn the if/else, if/elif/else and ternary -conditional constructs available in Python. - -{{{ Shift to terminal and start ipython }}} - -To begin with let us start ipython, by typing:: - - ipython - -on the terminal - -Whenever we have two possible states that can occur depending on a -whether a certain condition we can use if/else construct in -Python. Say for example we have a variable "a" which stores integers -and we are required to find out whether the value of the variable "a" -is an even number or an odd number. To test out conditional statements -as an example, let us say the value of the variable "a" is 5:: - - a = 5 - -In such a case we can write the if/else block as:: - - if a % 2 == 0: - print "Even" - else: - print "Odd" - -When the value of the variable "a" is divided by 2 and the remainder -is 0 i.e. the result of the operation "a modulo 2" is 0 the condition -"a % 2 == 0" evaluates to True, so the code within the if block gets -executed. This means that the value of "a" is Even. - -If the operation "a modulo 2" is not 0 the condition "a % 2 == 0" -evaluates to False and hence the code block within else gets executed -which means that the value of "a" is Odd. - -Note in such a case only one of the two blocks get executed depending -on whether the condition is True or False. - -There is a very important sytactic element to understand here. All the -statements which are inside a certain code block are indented by 4 -spaces. The statement which starts a new code block after it, i.e. the -if statement in this example ends with a colon (:). So the next -immediate line will be inside the if block and hence indented by 4 -spaces. To come out of the code block we have to come back to the -previous indentation level as shown in the else line here. Again the -line following else will be in a new block so else line ends with a -colon and the following block of code is indented by 4. - -As we use if/else statement when we have a condition which can take -one of the two states, we may have conditions which can take more than -two states. In such a scenario Python provides if/elif/else -statements. Let us take an example. We have a variable "a" which holds -integer values. We need to print "positive" if the value of a is -positive, "negative" if it is negative and "zero" if the value of the -variable "a" is 0. Let us use if/elif/else ladder for it. For the -purposes of testing our code let us assume that the value of a is -3:: - - a = -3 - - if a > 0: - print "positive" - elif a < 0: - print "negative" - else: - print "zero" - -This if/elif/else ladder is self explanatory. All the syntax and rules -as said for if/else statements hold. The only addition here is the -elif statement which can have another condition of its own. - -Here, exactly one block of code is executed and that block of code -corresponds to the condition which first evaluates to True. Even if -there is a situation where multiple conditions evaluate to True all -the subsequent conditions other than the first one which evaluates to -True are neglected. Consequently, the else block gets executed if and -only if all the conditions evaluate to False. - -Also, the else block in both if/else statement and if/elif/else is -optional. We can have a single if statement or just if/elif statements -without having else block at all. Also, there can be any number of -elif's within an if/elif/else ladder. For example - -{{{ Show slide for this }}} - - if user == 'admin': - # Do admin operations - elif user == 'moderator': - # Do moderator operations - elif user == 'client': - # Do customer operations - -{{{ end of slide switch to ipython }}} - -is completely valid. Note that there are multiple elif blocks and there -is no else block. - -In addition to these conditional statements, Python provides a very -convenient ternary conditional operator. Let us take the following -example where we read the marks data from a data file which is -obtained as a string as we read a file. The marks can be in the range -of 0 to 100 or 'AA' if the student is absent. In such a case to obtain -the marks as an integer we can use the ternary conditional -operator. Let us say the string score is stored in score_str -variable:: - - score_str = 'AA' - -Now let us use the ternary conditional operator:: - - score = int(score_str) if score_str != 'AA' else 0 - -This is just the if/else statement block which written in a more -convenient form and is very helpful when we have only one statement -for each block. This conditional statement effectively means as we -would have exactly specified in the English language which will be -like score is integer of score_str is score_str is not 'AA' otherwise -it is 0. This means that we make the scores of the students who were -absent for the exam 0. - -Moving on, there are certain situations where we will have to no -operations or statements within the block of code. For example, we -have a code where we are waiting for the keyboard input. If the user -enters "s" as the input we would perform some operation nothing -otherwise. In such cases "pass" statement comes very handy:: - - a = raw_input("Enter 'c' to calculate and exit, 'd' to display the existing - results exit and 'x' to exit and any other key to continue: ") - - if a == 'c': - # Calculate the marks and exit - elif a == 'd': - # Display the results and exit - elif a == 'x': - # Exit the program - else: - pass - -In this case "pass" statement acts as a place holder for the block of -code. It is equivalent to a null operation. It literally does -nothing. So "pass" statement can be used as a null operation -statement, or it can used as a place holder when the actual code -implementation for a particular block of code is not known yet but has -to be filled up later. - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial session on conditional -statements in Python. In this tutorial session we learnt - - * What are conditional statements - * if/else statement - * if/elif/else statement - * Ternary conditional statement - C if X else Y - * and the "pass" statement - -{{{ 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 : Madhu - Internal Reviewer 1 : [potential reviewer: Puneeth] - Internal Reviewer 2 : [potential reviewer: Anoop] - External Reviewer : - diff -r d5248a15274c -r c77f7f5850dd conditionals/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conditionals/questions.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,79 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Given a variable ``time``, print ``Good Morning`` if it is less + than 12, otherwise ``Hello``. + + Answer:: + + if time < 12: + print "Good Morning" + + else: + print "Hello" + +#. Every ``if`` block must be followed by an ``else`` block. T or F? + + Answer: F + +#. Every ``if/elif/else`` ladder MUST end with an ``else`` block. T/F? + + Answer: F + +#. An if/elif/else ladder can have any number of elif blocks. T or F? + + Answer: T + +#. What will be printed at the end this code block:: + + x = 20 + + if x > 10: + print x * 100 + + Answer: IndentationError - Expected and indented block.. + +#. What will be printed at the end this code block:: + + x = 20 + + if x > 10: + print x * 100 + else: + print x + + Answer: SyntaxError + +#. What will be printed at the end this code block:: + + x = 20 + + if x > 10: + print x * 100 + else: + print x + + Answer: 2000 + +#. Convert the if else ladder below into a ternary conditional + statement:: + + x = 20 + + if x > 10: + print x * 100 + else: + print x + + Answer: print x * 100 if x > 10 else x + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Question 1 +2. Question 2 diff -r d5248a15274c -r c77f7f5850dd conditionals/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conditionals/quickref.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd conditionals/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conditionals/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,192 @@ +.. Objectives +.. ---------- + +.. Clearly state the objectives of the LO (along with RBT level) + +.. Prerequisites +.. ------------- + +.. 1. Name of LO-1 +.. 2. Name of LO-2 +.. 3. Name of LO-3 + +.. Author : Madhu + Internal Reviewer : + External Reviewer : + Checklist 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 learn the basic conditional constructs +available in Python. We learn the if/else, if/elif/else and ternary +conditional constructs available in Python. + +{{{ Shift to terminal and start ipython }}} + +To begin with let us start ipython, by typing:: + + ipython + +on the terminal + +Whenever we have two possible states that can occur depending on a +whether a certain condition we can use if/else construct in +Python. Say for example we have a variable "a" which stores integers +and we are required to find out whether the value of the variable "a" +is an even number or an odd number. To test out conditional statements +as an example, let us say the value of the variable "a" is 5:: + + a = 5 + +In such a case we can write the if/else block as:: + + if a % 2 == 0: + print "Even" + else: + print "Odd" + +When the value of the variable "a" is divided by 2 and the remainder +is 0 i.e. the result of the operation "a modulo 2" is 0 the condition +"a % 2 == 0" evaluates to True, so the code within the if block gets +executed. This means that the value of "a" is Even. + +If the operation "a modulo 2" is not 0 the condition "a % 2 == 0" +evaluates to False and hence the code block within else gets executed +which means that the value of "a" is Odd. + +Note in such a case only one of the two blocks get executed depending +on whether the condition is True or False. + +There is a very important sytactic element to understand here. All the +statements which are inside a certain code block are indented by 4 +spaces. The statement which starts a new code block after it, i.e. the +if statement in this example ends with a colon (:). So the next +immediate line will be inside the if block and hence indented by 4 +spaces. To come out of the code block we have to come back to the +previous indentation level as shown in the else line here. Again the +line following else will be in a new block so else line ends with a +colon and the following block of code is indented by 4. + +As we use if/else statement when we have a condition which can take +one of the two states, we may have conditions which can take more than +two states. In such a scenario Python provides if/elif/else +statements. Let us take an example. We have a variable "a" which holds +integer values. We need to print "positive" if the value of a is +positive, "negative" if it is negative and "zero" if the value of the +variable "a" is 0. Let us use if/elif/else ladder for it. For the +purposes of testing our code let us assume that the value of a is -3:: + + a = -3 + + if a > 0: + print "positive" + elif a < 0: + print "negative" + else: + print "zero" + +This if/elif/else ladder is self explanatory. All the syntax and rules +as said for if/else statements hold. The only addition here is the +elif statement which can have another condition of its own. + +Here, exactly one block of code is executed and that block of code +corresponds to the condition which first evaluates to True. Even if +there is a situation where multiple conditions evaluate to True all +the subsequent conditions other than the first one which evaluates to +True are neglected. Consequently, the else block gets executed if and +only if all the conditions evaluate to False. + +Also, the else block in both if/else statement and if/elif/else is +optional. We can have a single if statement or just if/elif statements +without having else block at all. Also, there can be any number of +elif's within an if/elif/else ladder. For example + +{{{ Show slide for this }}} + + if user == 'admin': + # Do admin operations + elif user == 'moderator': + # Do moderator operations + elif user == 'client': + # Do customer operations + +{{{ end of slide switch to ipython }}} + +is completely valid. Note that there are multiple elif blocks and there +is no else block. + +In addition to these conditional statements, Python provides a very +convenient ternary conditional operator. Let us take the following +example where we read the marks data from a data file which is +obtained as a string as we read a file. The marks can be in the range +of 0 to 100 or 'AA' if the student is absent. In such a case to obtain +the marks as an integer we can use the ternary conditional +operator. Let us say the string score is stored in score_str +variable:: + + score_str = 'AA' + +Now let us use the ternary conditional operator:: + + score = int(score_str) if score_str != 'AA' else 0 + +This is just the if/else statement block which written in a more +convenient form and is very helpful when we have only one statement +for each block. This conditional statement effectively means as we +would have exactly specified in the English language which will be +like score is integer of score_str is score_str is not 'AA' otherwise +it is 0. This means that we make the scores of the students who were +absent for the exam 0. + +Moving on, there are certain situations where we will have to no +operations or statements within the block of code. For example, we +have a code where we are waiting for the keyboard input. If the user +enters "s" as the input we would perform some operation nothing +otherwise. In such cases "pass" statement comes very handy:: + + a = raw_input("Enter 'c' to calculate and exit, 'd' to display the existing + results exit and 'x' to exit and any other key to continue: ") + + if a == 'c': + # Calculate the marks and exit + elif a == 'd': + # Display the results and exit + elif a == 'x': + # Exit the program + else: + pass + +In this case "pass" statement acts as a place holder for the block of +code. It is equivalent to a null operation. It literally does +nothing. So "pass" statement can be used as a null operation +statement, or it can used as a place holder when the actual code +implementation for a particular block of code is not known yet but has +to be filled up later. + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial session on conditional +statements in Python. In this tutorial session we learnt + + * What are conditional statements + * if/else statement + * if/elif/else statement + * Ternary conditional statement - C if X else Y + * and the "pass" statement + +{{{ 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 d5248a15274c -r c77f7f5850dd conditionals/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conditionals/slides.org Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd conditionals/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conditionals/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd dictionaries/script.rst --- a/dictionaries/script.rst Tue Oct 12 11:44:33 2010 +0530 +++ b/dictionaries/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -1,11 +1,27 @@ -.. 8.4 LO: dictionaries (2) -.. ------------------------ -.. * empty -.. * filled -.. * accessing via keys -.. * .values(), .keys() -.. * in -.. * iteration +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Create dictionaries +.. #. Add data to dictionaries +.. #. Retrieve data +.. #. Familiarize using ``.keys()`` and ``.values()`` methods +.. #. Checking for container-ship of keys +.. #. Iterating over elements + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` installed. +.. #. getting started with ``ipython``. +.. #. basic datatypes. + +.. Author : Anoop Jacob Thomas + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + ============ Dictionaries @@ -176,8 +192,3 @@ {{{ switch to next slide, thank you slide }}} Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: diff -r d5248a15274c -r c77f7f5850dd getting-started-sagenotebook.rst --- a/getting-started-sagenotebook.rst Tue Oct 12 11:44:33 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,295 +0,0 @@ -Hello friends. Welcome to this spoken tutorial on Getting started with -sage and sage notebook. - -{{{ Show the slide containing the title }}} - -{{{ 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 move on now. - -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 much 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* }}} - -to use Sage and nothing else! The Sage notebook also provides a -convenient way of sharing and publishing our work which is very handy -when we use Sage for research or for 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. Worksheets are basically the 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 can configure our notebook, -the notebook server, we can 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. -Thankyou - -.. Author : Madhu - Internal Reviewer 1 : [potential reviewer: Anoop] - Internal Reviewer 2 : [potential reviewer: Puneeth] - External Reviewer : - diff -r d5248a15274c -r c77f7f5850dd getting-started-sagenotebook/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-sagenotebook/questions.rst Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-sagenotebook/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-sagenotebook/quickref.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-sagenotebook/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-sagenotebook/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,323 @@ +.. 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 : + External Reviewer : + Checklist OK? : [2010-10-05] + + +Script +------ + +Hello friends. Welcome to this spoken tutorial on Getting started with +sage and sage notebook. + +{{{ Show the slide containing the title }}} + +{{{ 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 move on now. + +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 much 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* }}} + +to use Sage and nothing else! The Sage notebook also provides a +convenient way of sharing and publishing our work which is very handy +when we use Sage for research or for 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. Worksheets are basically the 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 can configure our notebook, +the notebook server, we can 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 d5248a15274c -r c77f7f5850dd getting-started-sagenotebook/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-sagenotebook/slides.org Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-sagenotebook/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-sagenotebook/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-strings.rst --- a/getting-started-strings.rst Tue Oct 12 11:44:33 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,125 +0,0 @@ -Hello friends. Welcome to this spoken tutorial on Getting started with -strings. - -{{{ Show the slide containing the title }}} - -{{{ Show the slide containing the outline }}} - -In this tutorial, we will learn what do we actually mean by strings in -python, how python supports the use of strings. We will also learn -some of the operations that can be performed on strings. - -{{{ 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. This is true whatsoever, even if there is only one character -within the quotes - -{{{ 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' - -Having more than one control character to define strings come as very -handy when one of the control characters itself is part of the -string. For example:: - - "Python's string manipulation functions are very useful" - -In this case we use single quote for apostrophe. If we had only single -quote to define strings we should have a clumsy way of escaping the -single quote character to make it part of the string. Hence this is a -very handy feature. - -The triple quoted strings let us define multi-lines 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. - -Since strings are collections we can access individual items in the -string using the subscripts:: - - a[0] - -gives us the first character in the string. The indexing starts from 0 -for the first character up to n-1 for the last character. We can -access the strings from the end using negative indices:: - - a[-2] - -gives us second element from the end of the string - -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 the -string. Although there are some methods which let us to manipulate the -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 types of defining a string - * String concatenation and repeatition - * 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. -Thankyou - -.. Author : Madhu - Internal Reviewer 1 : [potential reviewer: Nishanth] - Internal Reviewer 2 : [potential reviewer: Amit] - External Reviewer : - diff -r d5248a15274c -r c77f7f5850dd getting-started-strings/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-strings/questions.rst Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-strings/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-strings/quickref.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-strings/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-strings/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,145 @@ +.. 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 : + External Reviewer : + Checklist 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 learn what do we actually mean by strings in +python, how python supports the use of strings. We will also learn +some of the operations that can be performed on strings. + +{{{ 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. This is true whatsoever, even if there is only one character +within the quotes + +{{{ 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' + +Having more than one control character to define strings come as very +handy when one of the control characters itself is part of the +string. For example:: + + "Python's string manipulation functions are very useful" + +In this case we use single quote for apostrophe. If we had only single +quote to define strings we should have a clumsy way of escaping the +single quote character to make it part of the string. Hence this is a +very handy feature. + +The triple quoted strings let us define multi-lines 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. + +Since strings are collections we can access individual items in the +string using the subscripts:: + + a[0] + +gives us the first character in the string. The indexing starts from 0 +for the first character up to n-1 for the last character. We can +access the strings from the end using negative indices:: + + a[-2] + +gives us second element from the end of the string + +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 the +string. Although there are some methods which let us to manipulate the +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 repeatition + * 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 d5248a15274c -r c77f7f5850dd getting-started-strings/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-strings/slides.org Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-strings/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-strings/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-with-arrays/script.rst --- a/getting-started-with-arrays/script.rst Tue Oct 12 11:44:33 2010 +0530 +++ b/getting-started-with-arrays/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -1,39 +1,60 @@ -.. 4.1 LO: getting started with arrays (2) [anoop] -.. ------------------------------------------------ -.. * why arrays -.. + speed - simply say -.. + array level operations -.. * creating arrays -.. + direct data -.. + list conversion -.. + homogeneous -.. + builtins - identitiy, zeros, -.. * array operations -.. + =+ - * /= +.. 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 : + Checklist 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 arrays, how to convert a list -into an array and also why an array is preferred over lists. And array -operations. +In this tutorial, we will learn about arrays, how to convert a list into an +array and also why an array is preferred over lists. And array operations. + +.. #[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, it can have only one type -of data type, either all integers, or strings, or float, and not a -mix. +Arrays are homogeneous data structures, unlike lists, arrays cannot have +heterogeneous data elements, that is, it can have only one type of data +type, either all integers, or strings, or float, and not a mix. + +.. #[Puneeth: Use multiple short sentences, rather than one long sentence + I would've written something like this. -Arrays are really fast in mathematical operations when compared to -lists, it is at least 80 to 100 times faster than lists. + Unlike lists, arrays are homogeneous data structures. They can have only + type of data, ....] + +Arrays are really fast in mathematical operations when compared to lists, +it is at least 80 to 100 times faster than lists. + +.. #[Puneeth: For what size of an array is that the comparison? {{{ switch to the next slide, creating arrays }}} @@ -42,39 +63,63 @@ I am assuming that you have your IPython interpreter running with the ``-pylab`` option, so that you have the required modules loaded. +.. #[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 here we created a one dimensional array. Also notice the -object we passed to create an array. Now let us see how to create a -two dimensional array. Pause here and try to do it yourself before -looking at the solution. +Notice that here we created a one dimensional array. Also notice the object +we passed to create an array. Now let us see how to create a two +dimensional array. Pause here and try to do it yourself before looking at +the solution. + +.. #[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.] This is how we create two dimensional arrays. + :: 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.] + Let us see an easy method of creating an array with elements 1 to 8. + :: ar = arange(1,9) +.. #[Puneeth: say, creating the same array as before. for some time I got +.. confused .] + And it created a single dimensional array of elements from 1 to 8. + :: print ar -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. +.. #[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, +We can use the function ``reshape()`` for that purpose and it can be done +as, + :: ar.reshape(2,4) @@ -84,14 +129,15 @@ {{{ 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`` +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, +Now we can convert the list to an array as, + :: a3 = array(l1) @@ -101,70 +147,96 @@ Create a three dimensional array of the order (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 object ``.shape``, let us check the shape of the arrays we have created so far, + +.. #[Puneeth: s/object/method ?] + :: a1.shape -``a1.shape`` object is a tuple, and since a1 is a single dimensional -array, it returned a tuple (4,). +``a1.shape`` object is a tuple, and since a1 is a single dimensional array, +it returned a tuple (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.] + {{{ Array can have only a single type of data }}} -Now let us try to create a new array with a mix of elements and see -what will happen, +.. #[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 expected an error as previously I said that an array can have -only homogeneous elements, but it didn't give an error. Let us check -the values in the new array created. In your IPython terminal type, +Well, we expected an error as previously I said that an array can have only +homogeneous elements, but it didn't give an error. Let us check the values +in the new array created. In your IPython terminal type, :: a4 -Did you notice it, +Did you notice it, {{{ switch to next slide, implicit type casting }}} -{{{ highlight all the array elements one by one using mouse -movements }}} +.. #[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.] -all the elements have been implicitly type casted as string, though -our first three elements were integers. +{{{ highlight all the array elements one by one using mouse movements }}} + +all the elements have been implicitly type casted as string, though our +first three elements were 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 }}} -An identity matrix is a square matrix in which all the diagonal -elements are one and rest of the elements zero. We can create an -identity matrix using the method ``identity()``. +.. #[Puneeth: something needs to motivate this. why are we suddenly talking +.. of an identity matrix?] + +An identity matrix is a square matrix in which all the diagonal elements +are one and rest of the elements zero. We can create an identity matrix +using the method ``identity()``. The function ``identity()`` takes an integer argument, + :: identity(3) -As you can see the identity method returned a three by three square -array with all the diagonal elements as one and the rest of the -elements as zero. +As you can see the identity method returned a three by three square array +with all the diagonal elements as one and the rest of the elements as zero. -``zeros()`` function accepts a tuple, which is the order of the array -we want to create, and it generates an array with all elements zero. +.. #[Puneeth: You say array here, matrix there -- it's a bit messed up. +.. Clarify, explicitly.] -{{{ switch to the next slide, problem statement of the solved exercise -1 }}} +``zeros()`` function accepts a tuple, which is the order of the array we +want to create, and it generates an array with all elements zero. -Let us creates an array of the order four by five with all the -elements zero. We can do it using the method 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)) @@ -216,8 +288,7 @@ a -We can use all the mathematical operations with arrays, Now let us try -this +We can use all the mathematical operations with arrays, Now let us try this :: a1 = array([1,2,3,4]) @@ -229,20 +300,25 @@ a1 * a2 -Returns an array with element by element multiplication, notice that -it does not perform matrix multiplication. +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, how to create an array, converting a list to -an array, basic array operations etc. +So this brings us to the end of this tutorial, in this tutorial we covered +basics of arrays, how to create an array, converting a list to an array, +basic array operations etc. + +.. #[Puneeth: s/how to create an array/creating an array] {{{ switch to next slide, thank you }}} Thank you! -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: +.. + Local Variables: + mode: rst + indent-tabs-mode: nil + sentence-end-double-space: nil + fill-column: 75 + End: diff -r d5248a15274c -r c77f7f5850dd getting-started-with-for/script.rst --- a/getting-started-with-for/script.rst Tue Oct 12 11:44:33 2010 +0530 +++ b/getting-started-with-for/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -1,12 +1,29 @@ -.. 3.2 LO: getting started with =for= (2) [anoop] -.. ----------------------------------------------- -.. * blocks in python -.. + (indentation) -.. * blocks in ipython -.. + ... prompt -.. + hitting enter -.. * =for= with a list -.. * =range= function +.. 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 : + Checklist OK? : [2010-10-05] + ============================= Getting started with for loop @@ -43,6 +60,11 @@ 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 }}} @@ -85,6 +107,8 @@ 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 @@ -151,6 +175,8 @@ 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 @@ -166,11 +192,14 @@ 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, "is", sqrt(each) + 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, which means you are still inside the @@ -178,6 +207,8 @@ 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. @@ -187,6 +218,9 @@ {{{ 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, :: @@ -214,6 +248,8 @@ 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 here we learned is how to use Python interpreter and IPython interpreter to specify blocks. But while we were generating the multiplication table we used something new, @@ -225,12 +261,14 @@ .. #[Nishanth]: Show some examples of range without the step argument May be give an exercise with negative numbers as arguments -Now, let us print all the odd numbers from 1 to 50. Let us do it in -our IPython interpreter for ease of use. - {{{ 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. @@ -248,7 +286,7 @@ 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, recap slide }}} +{{{ 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 @@ -265,9 +303,3 @@ {{{ switch to next slide, thank you slide }}} Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: Nishanth - Reviewer 2: Amit Sethi - External reviewer: - diff -r d5248a15274c -r c77f7f5850dd getting-started-with-for/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-for/slides.org Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-with-for/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-for/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-with-lists/getting_started_with_lists.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-lists/getting_started_with_lists.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,137 @@ +Hello friends and welcome to the tutorial on getting started with +lists. + + {{{ Show the slide containing title }}} + + {{{ Show the slide containing the outline slide }}} + +In this tutorial we will be getting acquainted with a python data +structure called lists. We will learn :: + + * How to create lists + * Structure of lists + * Access list elements + * Append elements to lists + * Deleting elements from lists + +List is a compound data type, it can contain data of other data +types. List is also a sequence data type, all the elements are in +order and there order has a meaning. + +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. + +* Filled lists + +Lets now define a list, nonempty and fill it with some random elements. + +nonempty = ['spam', 'eggs', 100, 1.234] + +Thus the simplest way of creating a list is typing out a sequence +of comma-separated values (items) between square brackets. +All the list items need not have the same data type. + + + +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 +integer and float. Thus we can put elements of heterogenous types in +lists. Thus list themselves can be one of the element types possible +in lists. Thus lists can also contain other lists. Example :: + + list_in_list=[[4,2,3,4],'and', 1, 2, 3, 4] + +We access list elements using the number of index. The +index begins from 0. So for list nonempty, nonempty[0] gives the +first element, nonempty[1] the second element and so on and +nonempty[3] the last element. :: + + nonempty[0] + nonempty[1] + nonempty[3] + +We can also access the elememts from the end using negative indices :: + + 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 + +As we can see non empty appends 'onemore' and 6 at the end. + + + +Using len function we can check the number of elements in the list +nonempty. In this case it being 6 :: + + 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 +should be :: + + a.remove(100) + +but what if their were two 100's. To check that lets do a small +experiment. :: + + a.append('spam') + a + a.remove('spam') + a + +If we check a 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. + + +{{{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. + + + +{{{ 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 d5248a15274c -r c77f7f5850dd getting-started-with-lists/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-lists/questions.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,47 @@ +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. + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Question 1 +2. Question 2 diff -r d5248a15274c -r c77f7f5850dd getting-started-with-lists/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-lists/quickref.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd getting-started-with-lists/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-lists/slides.org Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,35 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC +#+OPTIONS: H:5 num:t toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t + +#+TITLE: Plotting Data +#+AUTHOR: FOSSEE +#+DATE: 2010-09-14 Tue +#+EMAIL: info@fossee.in + +# \author[FOSSEE] {FOSSEE} + +# \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +# \date{} + +* Tutorial Plan +** How to create lists +** Structure of lists +** Access list elements +** Append elements to lists +** Deleting elements from lists + + +* Summary + + l=[1,2,3,4] + l[-1] + l.append(5) + del(l[2]) + len(l) + diff -r d5248a15274c -r c77f7f5850dd getting-started-with-lists/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-lists/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd manipulating-lists.rst --- a/manipulating-lists.rst Tue Oct 12 11:44:33 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,180 +0,0 @@ -Hello friends. Welcome to this spoken tutorial on Getting started with -strings. - -{{{ Show the slide containing the title }}} - -{{{ Show the slide containing the outline }}} - -We have already learnt a lot about Lists in Python. In this tutorial, -we will learn more about advanced features of Lists in Python. We will -see in detail how to concatenate two lists, slicing and striding of -lists, methods to sort and reverse the list. - -{{{ 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 the 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 -when ever 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 exluded. - -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] - -So if we don't specify the step it is by default 1. Similary 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". - -The other basic operation that we can perform on list is concatenation -of two or more lists. We can combine two lists by using the "plus" -operator. Say we have - -{{{ 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 touching anything in the existing lists which are the -operands of the concatenation operation. - -We know that list is a collection of data. Whenever we have a -collection we run into situations where we want to start 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] - -Since the sort method sorts the list inplace 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) - -Similarly to perform certain operations on the list we would like to -reverse the list. Python provides reverse method which again 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. If we want to obtain the reverse -of a list keeping the original list intact we can use the Python -built-in function reversed. reversed function returns a new list which -is the reverse of the list which was passed as the argument to the -reversed function:: - - a = [1, 2, 3, 4, 5] - reversed(a) - -We can also store this new reversed list in another list variable. - -{{{ Show summary slide }}} - -This brings us to the end of another session. In this tutorial session -we learnt - - * How to define strings - * Different types of defining a string - * String concatenation and repeatition - * Accessing individual elements of the string - * Immutability of strings - -{{{ 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 : Madhu - Internal Reviewer 1 : [potential reviewer: Nishanth] - Internal Reviewer 2 : [potential reviewer: Amit] - External Reviewer : - diff -r d5248a15274c -r c77f7f5850dd manipulating-lists/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-lists/questions.rst Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd manipulating-lists/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-lists/quickref.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd manipulating-lists/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-lists/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,196 @@ +.. Objectives +.. ---------- + +.. Clearly state the objectives of the LO (along with RBT level) + +.. Prerequisites +.. ------------- + +.. 1. getting started with lists +.. 2. +.. 3. + +.. Author : Madhu + Internal Reviewer : + External Reviewer : + Checklist 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 a lot about Lists in Python. In this tutorial, +we will learn more about advanced features of Lists in Python. We will +see in detail how to concatenate two lists, slicing and striding of +lists, methods to sort and reverse the list. + +{{{ 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 the 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 +when ever 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. + +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] + +So if we don't specify the step it is by default 1. Similary 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". + +The other basic operation that we can perform on list is concatenation +of two or more lists. We can combine two lists by using the "plus" +operator. Say we have + +{{{ 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 touching anything in the existing lists which are the +operands of the concatenation operation. + +We know that list is a collection of data. Whenever we have a +collection we run into situations where we want to start 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] + +Since the sort method sorts the list inplace 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) + +Similarly to perform certain operations on the list we would like to +reverse the list. Python provides reverse method which again 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. If we want to obtain the reverse +of a list keeping the original list intact we can use the Python +built-in function reversed. reversed function returns a new list which +is the reverse of the list which was passed as the argument to the +reversed function:: + + a = [1, 2, 3, 4, 5] + reversed(a) + +We can also store this new reversed list in another list variable. + +{{{ Show summary slide }}} + +This brings us to the end of another session. In this tutorial session +we learnt + + * How to define strings + * Different types of defining a string + * String concatenation and repeatition + * Accessing individual elements of the string + * Immutability of strings + +{{{ 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 d5248a15274c -r c77f7f5850dd manipulating-lists/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-lists/slides.org Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd manipulating-lists/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-lists/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd matrices/script.rst --- a/matrices/script.rst Tue Oct 12 11:44:33 2010 +0530 +++ b/matrices/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -1,17 +1,35 @@ -.. 4.3 LO: Matrices (3) [anoop] -.. ----------------------------- -.. * creating matrices -.. + direct data -.. + list conversion -.. + builtins - identitiy, zeros, -.. * matrix operations -.. + + - * / -.. + dot -.. + inv -.. + det -.. + eig -.. + norm -.. + svd +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Create matrices using data. +.. #. Create matrices from lists. +.. #. Basic matrix operations. +.. #. Use ``inv()`` function to find inverse of a matrix. +.. #. Use ``det()`` function to find determinant of a matrix. +.. #. Use ``eig()`` and ``eigvals()`` functions to find eigen values + and vectors +.. #. Use ``norm()`` function to find norm of a matrix. +.. #. Use ``svd()`` function to find singular value decomposition of a + matrix. + + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` and ``pylab`` installed. +.. #. getting started with ``ipython``. +.. #. getting started with lists. +.. #. getting started with arrays. +.. #. accessing part of arrays. + + +.. Author : Anoop Jacob Thomas + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + ======== Matrices @@ -22,8 +40,10 @@ {{{ switch to next slide, outline slide }}} -In this tutorial we will learn about matrices, creating matrices and -matrix operations. +In this tutorial we will learn about matrices, creating matrices using +direct data, by converting a list, matrix operations. Finding inverse +of a matrix, determinant of a matrix, eigen values and eigen vectors +of a matrix, norm and singular value decomposition of matrices. {{{ creating a matrix }}} @@ -88,6 +108,8 @@ multiply(m3,m2) +{{{ switch to next slide, Matrix multiplication (cont'd) }}} + Now let us see an example for matrix multiplication. For doing matrix multiplication we need to have two matrices of the order n by m and m by r and the resulting matrix will be of the order n by r. Thus let us @@ -108,11 +130,15 @@ {{{ switch to next slide, recall from arrays }}} -As we already saw in arrays, the functions ``identity()``, -``zeros()``, ``zeros_like()``, ``ones()``, ``ones_like()`` may also be -used with matrices. +As we already saw in arrays, the functions ``identity()`` which +creates an identity matrix of the order n by n, ``zeros()`` which +creates a matrix of the order m by n with all zeros, ``zeros_like()`` +which creates a matrix with zeros with the shape of the matrix passed, +``ones()`` which creates a matrix of order m by n with all ones, +``ones_like()`` which creates a matrix with ones with the shape of the +matrix passed. These functions can also be used with matrices. -{{{ switch to next slide, matrix operations }}} +{{{ switch to next slide, more matrix operations }}} To find out the transpose of a matrix we can do, :: @@ -178,8 +204,6 @@ norm(im5) -Euclidean norm is also called Frobenius norm. - And to find out the Infinity norm of the matrix im5, we do, :: diff -r d5248a15274c -r c77f7f5850dd matrices/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/matrices/slides.org Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,176 @@ +#+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: Matrices +#+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 + - Creating Matrices + - using direct data + - converting a list + - Matrix operations + - Inverse of matrix + - Determinant of matrix + - Eigen values and Eigen vectors of matrices + - Norm of matrix + - Singular Value Decomposition of matrices + +* Creating a matrix + - Creating a matrix using direct data + : In []: m1 = matrix([1, 2, 3, 4]) + - Creating a matrix using lists + : In []: l1 = [[1,2,3,4],[5,6,7,8]] + : In []: m2 = matrix(l1) + - A matrix is basically an array + : In []: m3 = array([[5,6,7,8],[9,10,11,12]]) + +* Matrix operations + - Element-wise addition (both matrix should be of order ~mXn~) + : In []: m3 + m2 + - Element-wise subtraction (both matrix should be of order ~mXn~) + : In []: m3 - m2 +* Matrix Multiplication + - Matrix Multiplication + : In []: m3 * m2 + : Out []: ValueError: objects are not aligned + - Element-wise multiplication using ~multiply()~ + : multiply(m3, m2) + +* Matrix Multiplication (cont'd) + - Create two compatible matrices of order ~nXm~ and ~mXr~ + : In []: m1.shape + - matrix m1 is of order ~1 X 4~ + - Creating another matrix of order ~4 X 2~ + : In []: m4 = matrix([[1,2],[3,4],[5,6],[7,8]]) + - Matrix multiplication + : In []: m1 * m4 +* Recall from ~array~ + - The functions + - ~identity(n)~ - + creates an identity matrix of order ~nXn~ + - ~zeros((m,n))~ - + creates a matrix of order ~mXn~ with 0's + - ~zeros_like(A)~ - + creates a matrix with 0's similar to the shape of matrix ~A~ + - ~ones((m,n))~ + creates a matrix of order ~mXn~ with 1's + - ~ones_like(A)~ + creates a matrix with 1's similar to the shape of matrix ~A~ + Can also be used with matrices + +* More matrix operations + Transpose of a matrix + : In []: m4.T +* Exercise 1 : Frobenius norm \& inverse + Find out the Frobenius norm of inverse of a ~4 X 4~ matrix. + : + The matrix is + : m5 = matrix(arange(1,17).reshape(4,4)) + - Inverse of A, + - + #+begin_latex + $A^{-1} = inv(A)$ + #+end_latex + - Frobenius norm is defined as, + - + #+begin_latex + $||A||_F = [\sum_{i,j} abs(a_{i,j})^2]^{1/2}$ + #+end_latex + +* Exercise 2: Infinity norm + Find the infinity norm of the matrix ~im5~ + : + - Infinity norm is defined as, + #+begin_latex + $max([\sum_{i} abs(a_{i})^2])$ + #+end_latex +* ~norm()~ method + - Frobenius norm + : In []: norm(im5) + - Infinity norm + : In []: norm(im5, ord=inf) +* Determinant + Find out the determinant of the matrix m5 + : + - determinant can be found out using + - ~det(A)~ - returns the determinant of matrix ~A~ +* eigen values \& eigen vectors + Find out the eigen values and eigen vectors of the matrix ~m5~. + : + - eigen values and vectors can be found out using + : In []: eig(m5) + returns a tuple of /eigen values/ and /eigen vectors/ + - /eigen values/ in tuple + - ~In []: eig(m5)[0]~ + - /eigen vectors/ in tuple + - ~In []: eig(m5)[1]~ + - Computing /eigen values/ using ~eigvals()~ + : In []: eigvals(m5) +* Singular Value Decomposition (~svd~) + #+begin_latex + $M = U \Sigma V^*$ + #+end_latex + - U, an ~mXm~ unitary matrix over K. + - + #+begin_latex + $\Sigma$ + #+end_latex + , an ~mXn~ diagonal matrix with non-negative real numbers on diagonal. + - + #+begin_latex + $V^*$ + #+end_latex + , an ~nXn~ unitary matrix over K, denotes the conjugate transpose of V. + - SVD of matrix ~m5~ can be found out as, + : In []: svd(m5) +* Summary + - Matrices + - creating matrices + - Matrix operations + - Inverse (~inv()~) + - Determinant (~det()~) + - Norm (~norm()~) + - Eigen values \& vectors (~eig(), eigvals()~) + - Singular Value Decomposition (~svd()~) + +* 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 d5248a15274c -r c77f7f5850dd matrices/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/matrices/slides.tex Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,357 @@ +% Created 2010-10-12 Tue 14:28 +\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{Matrices} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Creating Matrices + +\begin{itemize} +\item using direct data +\item converting a list +\end{itemize} + +\item Matrix operations +\item Inverse of matrix +\item Determinant of matrix +\item Eigen values and Eigen vectors of matrices +\item Norm of matrix +\item Singular Value Decomposition of matrices +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Creating a matrix} +\label{sec-2} + +\begin{itemize} +\item Creating a matrix using direct data +\end{itemize} + +\begin{verbatim} + In []: m1 = matrix([1, 2, 3, 4]) +\end{verbatim} + +\begin{itemize} +\item Creating a matrix using lists +\end{itemize} + +\begin{verbatim} + In []: l1 = [[1,2,3,4],[5,6,7,8]] + In []: m2 = matrix(l1) +\end{verbatim} + +\begin{itemize} +\item A matrix is basically an array +\end{itemize} + +\begin{verbatim} + In []: m3 = array([[5,6,7,8],[9,10,11,12]]) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Matrix operations} +\label{sec-3} + +\begin{itemize} +\item Element-wise addition (both matrix should be of order \texttt{mXn}) +\begin{verbatim} + In []: m3 + m2 +\end{verbatim} + +\item Element-wise subtraction (both matrix should be of order \texttt{mXn}) +\begin{verbatim} + In []: m3 - m2 +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Matrix Multiplication} +\label{sec-4} + +\begin{itemize} +\item Matrix Multiplication +\begin{verbatim} + In []: m3 * m2 + Out []: ValueError: objects are not aligned +\end{verbatim} + +\item Element-wise multiplication using \texttt{multiply()} +\begin{verbatim} + multiply(m3, m2) +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Matrix Multiplication (cont'd)} +\label{sec-5} + +\begin{itemize} +\item Create two compatible matrices of order \texttt{nXm} and \texttt{mXr} +\begin{verbatim} + In []: m1.shape +\end{verbatim} + + +\begin{itemize} +\item matrix m1 is of order \texttt{1 X 4} +\end{itemize} + +\item Creating another matrix of order \texttt{4 X 2} +\begin{verbatim} + In []: m4 = matrix([[1,2],[3,4],[5,6],[7,8]]) +\end{verbatim} + +\item Matrix multiplication +\begin{verbatim} + In []: m1 * m4 +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Recall from \texttt{array}} +\label{sec-6} + +\begin{itemize} +\item The functions + +\begin{itemize} +\item \texttt{identity(n)} - + creates an identity matrix of order \texttt{nXn} +\item \texttt{zeros((m,n))} - + creates a matrix of order \texttt{mXn} with 0's +\item \texttt{zeros\_like(A)} - + creates a matrix with 0's similar to the shape of matrix \texttt{A} +\item \texttt{ones((m,n))} + creates a matrix of order \texttt{mXn} with 1's +\item \texttt{ones\_like(A)} + creates a matrix with 1's similar to the shape of matrix \texttt{A} +\end{itemize} + +\end{itemize} + + Can also be used with matrices +\end{frame} +\begin{frame}[fragile] +\frametitle{More matrix operations} +\label{sec-7} + + Transpose of a matrix +\begin{verbatim} + In []: m4.T +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 1 : Frobenius norm \& inverse} +\label{sec-8} + + Find out the Frobenius norm of inverse of a \texttt{4 X 4} matrix. +\begin{verbatim} + +\end{verbatim} + + The matrix is +\begin{verbatim} + m5 = matrix(arange(1,17).reshape(4,4)) +\end{verbatim} + +\begin{itemize} +\item Inverse of A, + +\begin{itemize} +\item $A^{-1} = inv(A)$ +\end{itemize} + +\item Frobenius norm is defined as, + +\begin{itemize} +\item $||A||_F = [\sum_{i,j} abs(a_{i,j})^2]^{1/2}$ +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 2: Infinity norm} +\label{sec-9} + + Find the infinity norm of the matrix \texttt{im5} +\begin{verbatim} + +\end{verbatim} + +\begin{itemize} +\item Infinity norm is defined as, + $max([\sum_{i} abs(a_{i})^2])$ +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{norm()} method} +\label{sec-10} + +\begin{itemize} +\item Frobenius norm +\begin{verbatim} + In []: norm(im5) +\end{verbatim} + +\item Infinity norm +\begin{verbatim} + In []: norm(im5, ord=inf) +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Determinant} +\label{sec-11} + + Find out the determinant of the matrix m5 +\begin{verbatim} + +\end{verbatim} + +\begin{itemize} +\item determinant can be found out using + +\begin{itemize} +\item \texttt{det(A)} - returns the determinant of matrix \texttt{A} +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{eigen values \& eigen vectors} +\label{sec-12} + + Find out the eigen values and eigen vectors of the matrix \texttt{m5}. +\begin{verbatim} + +\end{verbatim} + +\begin{itemize} +\item eigen values and vectors can be found out using +\begin{verbatim} + In []: eig(m5) +\end{verbatim} + + returns a tuple of \emph{eigen values} and \emph{eigen vectors} +\item \emph{eigen values} in tuple + +\begin{itemize} +\item \texttt{In []: eig(m5)[0]} +\end{itemize} + +\item \emph{eigen vectors} in tuple + +\begin{itemize} +\item \texttt{In []: eig(m5)[1]} +\end{itemize} + +\item Computing \emph{eigen values} using \texttt{eigvals()} +\begin{verbatim} + In []: eigvals(m5) +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Singular Value Decomposition (\texttt{svd})} +\label{sec-13} + + $M = U \Sigma V^*$ +\begin{itemize} +\item U, an \texttt{mXm} unitary matrix over K. +\item $\Sigma$ + , an \texttt{mXn} diagonal matrix with non-negative real numbers on diagonal. +\item $V^*$ + , an \texttt{nXn} unitary matrix over K, denotes the conjugate transpose of V. +\item SVD of matrix \texttt{m5} can be found out as, +\end{itemize} + +\begin{verbatim} + In []: svd(m5) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-14} + +\begin{itemize} +\item Matrices + +\begin{itemize} +\item creating matrices +\end{itemize} + +\item Matrix operations +\item Inverse (\texttt{inv()}) +\item Determinant (\texttt{det()}) +\item Norm (\texttt{norm()}) +\item Eigen values \& vectors (\texttt{eig(), eigvals()}) +\item Singular Value Decomposition (\texttt{svd()}) +\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 d5248a15274c -r c77f7f5850dd multiple-plots.rst --- a/multiple-plots.rst Tue Oct 12 11:44:33 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,362 +0,0 @@ -Hello friends. Welcome to this spoken tutorial on Multiple plots. - -{{{ Show the slide containing the title }}} - -{{{ 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 the 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 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. -Thankyou - -.. Author : Madhu - Internal Reviewer 1 : [potential reviewer: Puneeth] - Internal Reviewer 2 : Nishanth - External Reviewer : - diff -r d5248a15274c -r c77f7f5850dd multiple-plots/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple-plots/questions.rst Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd multiple-plots/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple-plots/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,383 @@ +.. 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 : + +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 the 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 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 d5248a15274c -r c77f7f5850dd multiple-plots/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple-plots/slides.org Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd multiple-plots/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple-plots/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd other-type-of-plots/script.rst --- a/other-type-of-plots/script.rst Tue Oct 12 11:44:33 2010 +0530 +++ b/other-type-of-plots/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -1,10 +1,27 @@ -.. 2.4 LO: other types of plots (3) [anoop] -.. ----------------------------------------- -.. * scatter -.. * pie chart -.. * bar chart -.. * log -.. * illustration of other plots, matplotlib help +.. 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 : + External Reviewer : + Checklist OK? : [2010-10-05] + =================== Other type of plots @@ -17,12 +34,12 @@ {{{ show the outline slide }}} In this tutorial we will cover scatter plot, pie chart, bar chart and -log plot. We will also see few other plots and also introduce you to +loglog plot. We will also see few other plots and also introduce you to the matplotlib help. Let us start with scatter plot. -{{{ switch to the next slide }}} +{{{ 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 @@ -55,12 +72,14 @@ {{{ close the file and switch to the terminal }}} To produce the scatter plot first we need to load the data from the -file using ``loadtxt``. We learned in one of the previous sessions, +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())) +{{{ switch to next slide, ``scatter`` function }}} + Now in-order to generate the scatter graph we will use the function ``scatter()`` :: @@ -75,9 +94,11 @@ problem to be tried out }}} Now here is a question for you to try out, plot the same data with red -diamonds. +diamonds markers. -**Clue** - *try scatter? in your ipython interpreter* +.. **Clue** - *try scatter? in your ipython interpreter* + +Pause here and solve the question before moving on. .. scatter(year,profit,color='r',marker='d') @@ -95,6 +116,8 @@ the same data from file ``company-a-data.txt``. So let us reuse the data we have loaded from the file previously. +{{{ switch to next slide, ``pie()`` function }}} + We can plot the pie chart using the function ``pie()``. :: @@ -111,7 +134,9 @@ 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* +.. **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')) @@ -121,7 +146,7 @@ with rectangular bars with lengths proportional to the values that they represent. -{{{ switch to the slide showing the problem statement of third +{{{ switch to the slide showing the problem statement of fifth exercise question }}} Plot a bar chart representing the profit percentage of company A, with @@ -129,6 +154,8 @@ 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()``. :: @@ -143,13 +170,14 @@ 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. +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* +.. **Clue** - *try bar? in your ipython interpreter* .. bar(year,profit,fill=False,hatch='/') -{{{ switch to the slide which says about bar chart }}} +{{{ switch to the slide which says about log-log graph }}} Now let us move on to log-log plot. A log-log graph or log-log plot is a two-dimensional graph of numerical data that uses logarithmic scales @@ -170,6 +198,8 @@ 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, :: @@ -200,7 +230,7 @@ matplotlib.sourceforge.net/users/screenshots.html and also at matplotlib.sourceforge.net/gallery.html -{{{ switch to recap slide }}} +{{{ 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 @@ -209,8 +239,3 @@ {{{ switch to the thank you slide }}} Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: diff -r d5248a15274c -r c77f7f5850dd other-type-of-plots/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other-type-of-plots/slides.org Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd other-type-of-plots/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other-type-of-plots/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd plotting-data/plotting-data.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting-data/plotting-data.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,136 @@ +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. 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'. :: + + 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 d5248a15274c -r c77f7f5850dd plotting-data/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting-data/questions.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,56 @@ +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 points ? + + By passing an extra parameter '.'. + +4. What does the parameter 'o' do ? + + It plots large points. + +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. Question 1 +2. Question 2 diff -r d5248a15274c -r c77f7f5850dd plotting-data/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting-data/slides.org Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,84 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC +#+OPTIONS: H:5 num:t toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t + +#+TITLE: Plotting Experimental Data +#+AUTHOR: FOSSEE +#+DATE: 2010-09-14 Tue +#+EMAIL: info@fossee.in + +# \author[FOSSEE] {FOSSEE} + +# \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +# \date{} + +* Tutorial Plan +** Plotting Experiment Data and Error Bars +* Pre-requisites +** Plotting simple analytical Functions +* plot L vs. T^2 + +#+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 + : In []: L = [0.1, 0.2, 0.3, 0.4, 0.5, + : 0.6, 0.7, 0.8, 0.9] + : In []: t = [0.69, 0.90, 1.19, + : 1.30, 1.47, 1.58, + : 1.77, 1.83, 1.94] +* square() + : In []: tsquare=square(t) + + : array([ 0.4761, 0.81 , 1.4161, 1.69 , 2.1609, 2.4964, 3.1329, + : 3.3489, 3.7636]) + + +* Plotting + : In[]: plot(L,t,.) + + + : In[]: plot(L,t,o) + +* Adding an Error Column + + + | L | T | /Delta L | /Delta T | + | 0.1 | 0.69 | 0.08 | 0.04 | + | 0.2 | 0.90 | 0.09 | 0.08 | + | 0.3 | 1.19 | 0.07 | 0.11 | + | 0.4 | 1.30 | 0.05 | 0.05 | + | 0.5 | 1.47 | 0.06 | 0.03 | + | 0.6 | 1.58 | 0.00 | 0.03 | + | 0.7 | 1.77 | 0.06 | 0.01 | + | 0.8 | 1.83 | 0.06 | 0.07 | + | 0.9 | 1.94 | 0.01 | 0.01 | + + +* Plotting Error bar + + : In[]: delta_L= [0.08,0.09,0.07,0.05,0.16, + : 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] + + + diff -r d5248a15274c -r c77f7f5850dd plotui/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotui/questions.rst Mon Oct 18 21:11:34 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. Question 1 +2. Question 2 diff -r d5248a15274c -r c77f7f5850dd plotui/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotui/quickref.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd plotui/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotui/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,182 @@ +Hello and welcome to the tutorial on creating simple plots using +Python.This tutorial is presented by the Fossee group. +{{{ Show the Title Slide }}} + +I hope you have IPython running on your computer. + +In this tutorial we will look at plot command and also how to study +the plot using the UI. + +{{{ Show Outline Slide }}} + +Lets start ipython on your shell, type :: + + $ipython -pylab + + +Pylab is a python library which provides plotting functionality.It +also provides many other important mathematical and scientific +functions. After running IPython -pylab in your shell if at the top of +the result of this command, you see something like :: + + + `ERROR: matplotlib could NOT be imported! Starting normal + IPython.` + + +{{{ Slide with Error written on it }}} + +Then you have to install matplotlib and run this command again. + +Now type in your ipython shell :: + + In[]: linpace? + + + +as the documentation says, it returns `num` evenly spaced samples, +calculated over the interval start and stop. To illustrate this, lets +do it form 1 to 100 and try 100 points. :: + + In[]: linspace(1,100,100) + +As you can see a sequence of numbers from 1 to 100 appears. + +Now lets try 200 points between 0 and 1 you do this by typing :: + + + In[]: linspace(0,1,200) + +0 for start , 1 for stop and 200 for no of points. In linspace +the start and stop points can be integers, decimals , or +constants. Let's try and get 100 points between -pi to pi. Type :: + + In[]: p = linspace(-pi,pi,100) + + +'pi' here is constant defined by pylab. Save this to the variable, p +. + +If you now :: + + In[]: len(p) + +You will get the no. of points. len function gives the no of elements +of a sequence. + + +Let's try and plot a cosine curve between -pi and pi using these +points. Simply type :: + + + In[]: plot(p,cos(points)) + +Here cos(points) gets the cosine value at every corresponding point to +p. + + +We can also save cos(points) to variable cosine and plot it using +plot.:: + + In[]: cosine=cos(points) + + In[]: plot(p,cosine) + + + +Now do :: + + In[]: clf() + +this will clear the plot. + +This is done because any other plot we try to make shall come on the +same drawing area. As we do not wish to clutter the area with +overlaid plots , we just clear it with clf(). Now lets try a sine +plot. :: + + + In []: plot(p,sin(p)) + + + + +The Window on which the plot appears can be used to study it better. + +First of all moving the mouse around gives us the point where mouse +points at. + +Also we have some buttons the right most among them is +for saving the file. + +Just click on it specifying the name of the file. We will save the plot +by the name sin_curve in pdf format. + + + +{{{ Action corelating with the words }}} + +As you can see I can specify format of file from the dropdown. + +Formats like png ,eps ,pdf, ps are available. + +Left to the save button is the slider button to specify the margins. + +{{{ Action corelating with the words }}} + +Left to this is zoom button to zoom into the plot. Just specify the +region to zoom into. +The button left to it can be used to move the axes of the plot. + +{{{ Action corelating with the words }}} + +The next two buttons with a left and right arrow icons change the state of the +plot and take it to the previous state it was in. It more or less acts like a +back and forward button in the browser. + +{{{ Action corelating with the words }}} + +The last one is 'home' referring to the initial plot. + +{{{ Action corelating with the words}}} + + + +{{{ Summary Slide }}} + + +In this tutorial we have looked at + +1. Starting Ipython with pylab + +2. Using linspace function to create `num` equaly spaced points in a region. + +3. Finding length of sequnces using len. + +4. Plotting mathematical functions using plot. + +4. Clearing drawing area using clf + +5. Using the UI of plot for studying it better . Using functionalities like save , zoom , moving the plots on x and y axis + +etc .. + + + +{{{ 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 d5248a15274c -r c77f7f5850dd plotui/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotui/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd progress.org --- a/progress.org Tue Oct 12 11:44:33 2010 +0530 +++ b/progress.org Mon Oct 18 21:11:34 2010 +0530 @@ -1,55 +1,55 @@ -| S.No | Name | Units | Author | 1st Review (Status) | 2nd Review (Status) | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 1.2 LO: | getting started with =ipython= | 2 | Punch | | | -| 1.3 LO: | using the =plot= command interactively | 2 | Amit | Anoop (Pending) | Puneeth (Pending) | -| 1.4 LO: | embellishing a plot | 2 | Nishanth | Anoop (Done) | Madhu (Done) | -| 1.5 LO: | saving plots | 2 | Anoop | | | -| 1.6 LO: | multiple plots | 3 | Madhu | Nishanth (Done) | Punch (Pending) | -| 1.7 LO: | additional features of IPython | 2 | Nishanth | Amit (Pending) | Madhu (Pending) | -| 1.8 LO: | module level assessment | 3 | Madhu | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 2.2 LO: | loading data from files | 3 | Punch | Nishanth (Done) | Anoop (Pending) | -| 2.3 LO: | plotting the data | 3 | Amit | Anoop (Pending) | Punch (Pending) | -| 2.4 LO: | other types of plots | 3 | Anoop | | | -| 2.5 LO: | module level assessment | 3 | Nishanth | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 3.1 LO: | getting started with lists | 2 | Amit | Madhu (Pending) | Nishanth (Done) | -| 3.2 LO: | getting started with =for= | 2 | Anoop | Nishanth (Done) | Amit (Done) | -| 3.3 LO: | getting started with strings | 2 | Madhu | | | -| 3.4 LO: | getting started with files | 3 | Punch | | | -| 3.5 LO: | parsing data | 3 | Nishanth | Amit (Done) | Punch (Pending) | -| 3.6 LO: | statistics | 2 | Amit | Anoop (Pending) | Puneeth (Pending) | -| 3.7 LO: | module level assessment | 3 | Madhu | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 4.1 LO: | getting started with arrays | 2 | Anoop | | | -| 4.2 LO: | accessing parts of arrays | 4 | Punch | | | -| 4.3 LO: | Matrices | 3 | Anoop | | | -| 4.4 LO: | Least square fit | 2 | Nishanth | Punch (Pending) | Anoop (Pending) | -| 4.5 LO: | Assessment | 3 | Punch | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 5.1 LO: | getting started with sage notebook | 3 | Madhu | | | -| 5.2 LO: | getting started with symbolics | 3 | Amit | Madhu (Pending) | Nishanth (Pending) | -| 5.3 LO: | using Sage | 4 | Punch | | | -| 5.4 LO: | using sage to teach | 3 | Nishanth | | | -| 5.5 LO: | Assessment | 3 | Anoop | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 6.1 LO: | basic datatypes & operators | 4 | Amit | Madhu (Pending) | Nishanth (Done) | -| 6.2 LO: | I/O | 1 | Nishanth | | | -| 6.3 LO: | conditionals | 2 | Madhu | | | -| 6.4 LO: | loops | 2 | Puneeth | | | -| 6.5 LO: | Assessment | 3 | Anoop | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 7.1 LO: | manipulating lists | 3 | Madhu | | | -| 7.2 LO: | manipulating strings | 2 | Punch | | | -| 7.3 LO: | getting started with tuples | 2 | Nishanth | | | -| 7.4 LO: | dictionaries | 2 | Anoop | | | -| 7.5 LO: | sets | 2 | Nishanth | | | -| 7.6 LO: | Assessment | 3 | Amit | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 8.1 LO: | getting started with functions | 3 | Nishanth | | | -| 8.2 LO: | advanced features of functions | 3 | Punch | | | -| 8.3 LO: | using python modules | 3 | Anoop | | | -| 8.4 LO: | writing python scripts | 2 | Nishanth | | | -| 8.5 LO: | testing and debugging | 2 | Amit | | | -| 8.6 LO: | Assessment | 3 | Madhu | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| +| S.No | Name | Units | Author | Review | Checklist | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 1.2 LO: | getting started with =ipython= | 2 | Punch | | | +| 1.3 LO: | using the =plot= command interactively | 2 | Amit | | | +| 1.4 LO: | embellishing a plot | 2 | Nishanth | Anoop (Done) | | +| 1.5 LO: | saving plots | 2 | Anoop | | | +| 1.6 LO: | multiple plots | 3 | Madhu | Nishanth (Done) | | +| 1.7 LO: | additional features of IPython | 2 | Nishanth | Amit (Pending) | | +| 1.8 LO: | module level assessment | 3 | Madhu | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 2.2 LO: | loading data from files | 3 | Punch | Nishanth (Done) | | +| 2.3 LO: | plotting the data | 3 | Amit | | | +| 2.4 LO: | other types of plots | 3 | Anoop | | | +| 2.5 LO: | module level assessment | 3 | Nishanth | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 3.1 LO: | getting started with lists | 2 | Amit | | | +| 3.2 LO: | getting started with =for= | 2 | Anoop | Nishanth (Done) | | +| 3.3 LO: | getting started with strings | 2 | Madhu | | | +| 3.4 LO: | getting started with files | 3 | Punch | | | +| 3.5 LO: | parsing data | 3 | Nishanth | Amit (Done) | | +| 3.6 LO: | statistics | 2 | Amit | | | +| 3.7 LO: | module level assessment | 3 | Madhu | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 4.1 LO: | getting started with arrays | 2 | Anoop | Punch (Done) | | +| 4.2 LO: | accessing parts of arrays | 4 | Punch | | | +| 4.3 LO: | Matrices | 3 | Anoop | | | +| 4.4 LO: | Least square fit | 2 | Nishanth | Punch (Pending) | | +| 4.5 LO: | Assessment | 3 | Punch | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 5.1 LO: | getting started with sage notebook | 3 | Madhu | | | +| 5.2 LO: | getting started with symbolics | 3 | Amit | | | +| 5.3 LO: | using Sage | 4 | Punch | | | +| 5.4 LO: | using sage to teach | 3 | Nishanth | | | +| 5.5 LO: | Assessment | 3 | Anoop | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 6.1 LO: | basic datatypes & operators | 4 | Amit | Punch (Pending) | | +| 6.2 LO: | I/O | 1 | Nishanth | | | +| 6.3 LO: | conditionals | 2 | Madhu | | | +| 6.4 LO: | loops | 2 | Puneeth | | | +| 6.5 LO: | Assessment | 3 | Anoop | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 7.1 LO: | manipulating lists | 3 | Madhu | | | +| 7.2 LO: | manipulating strings | 2 | Punch | | | +| 7.3 LO: | getting started with tuples | 2 | Nishanth | | | +| 7.4 LO: | dictionaries | 2 | Anoop | | | +| 7.5 LO: | sets | 2 | Nishanth | | | +| 7.6 LO: | Assessment | 3 | Amit | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 8.1 LO: | getting started with functions | 3 | Nishanth | | | +| 8.2 LO: | advanced features of functions | 3 | Punch | | | +| 8.3 LO: | using python modules | 3 | Anoop | | | +| 8.4 LO: | writing python scripts | 2 | Nishanth | | | +| 8.5 LO: | testing and debugging | 2 | Amit | | | +| 8.6 LO: | Assessment | 3 | Madhu | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| diff -r d5248a15274c -r c77f7f5850dd savefig/script.rst --- a/savefig/script.rst Tue Oct 12 11:44:33 2010 +0530 +++ b/savefig/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -1,9 +1,24 @@ -.. 2.5 LO: saving plots (2) -.. ------------------------- -.. * Outline -.. + basic savefig -.. + png, pdf, ps, eps, svg -.. + going to OS and looking at the file +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Saving plots using ``savefig()`` function. +.. #. Saving 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 : + External Reviewer : + Checklist OK? : [2010-10-05] + ======= Savefig @@ -134,8 +149,3 @@ {{{ switch to Thank you slide }}} Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: diff -r d5248a15274c -r c77f7f5850dd statistics.rst --- a/statistics.rst Tue Oct 12 11:44:33 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,165 +0,0 @@ -Hello friends and welcome to the tutorial on statistics using Python - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall learn - * Doing simple statistical operations in Python - * Applying these to real world problems - -You will need Ipython with pylab running on your computer -to use this tutorial. - -Also you will need to know about loading data using loadtxt to be -able to follow the real world application. - -We will first start with the most necessary statistical -operation i.e finding mean. - -We have a list of ages of a random group of people :: - - age_list=[4,45,23,34,34,38,65,42,32,7] - -One way of getting the mean could be getting sum of -all the elements and dividing by length of the list.:: - - sum_age_list =sum(age_list) - -sum function gives us the sum of the elements.:: - - mean_using_sum=sum_age_list/len(age_list) - -This obviously gives the mean age but python has another -method for getting the mean. This is the mean function:: - - mean(age_list) - -Mean can be used in more ways in case of 2 dimensional lists. -Take a two dimensional list :: - - two_dimension=[[1,5,6,8],[1,3,4,5]] - -the mean function used in default manner will give the mean of the -flattened sequence. Flattened sequence means the two lists taken -as if it was a single list of elements :: - - mean(two_dimension) - flattened_seq=[1,5,6,8,1,3,4,5] - mean(flattened_seq) - -As you can see both the results are same. The other is mean -of each column.:: - - mean(two_dimension,0) - array([ 1. , 4. , 5. , 6.5]) - -or along the two rows seperately.:: - - mean(two_dimension,1) - array([ 5. , 3.25]) - -We can see more option of mean using :: - - mean? - -Similarly we can calculate median and stanard deviation of a list -using the functions median and std:: - - median(age_list) - std(age_list) - - - -Now lets apply this to a real world example :: - -We will a data file that is at the a path -``/home/fossee/sslc2.txt``.It contains record of students and their -performance in one of the State Secondary Board Examination. It has -180, 000 lines of record. We are going to read it and process this -data. We can see the content of file by double clicking on it. It -might take some time to open since it is quite a large file. Please -don't edit the data. This file has a particular structure. - -We can do :: - - cat /home/fossee/sslc2.txt - -to check the contents of the file. - -Each line in the file is a set of 11 fields separated -by semi-colons Consider a sample line from this file. -A;015163;JOSEPH RAJ S;083;042;47;00;72;244;;; - -The following are the fields in any given line. -* Region Code which is 'A' -* Roll Number 015163 -* Name JOSEPH RAJ S -* Marks of 5 subjects: ** English 083 ** Hindi 042 ** Maths 47 ** -Science AA (Absent) ** Social 72 -* Total marks 244 -* - -Now lets try and find the mean of English marks of all students. - -For this we do. :: - - L=loadtxt('/home/fossee/sslc2.txt',usecols=(3,),delimiter=';') - L - mean(L) - -loadtxt function loads data from an external file.Delimiter specifies -the kind of character are the fields of data seperated by. -usecols specifies the columns to be used so (3,). The 'comma' is added -because usecols is a sequence. - -To get the median marks. :: - - median(L) - -Standard deviation. :: - - std(L) - - -Now lets try and and get the mean for all the subjects :: - - L=loadtxt('sslc2.txt',usecols=(3,4,5,6,7),delimiter=';') - mean(L,0) - array([ 73.55452504, 53.79828941, 62.83342759, 50.69806158, 63.17056881]) - -As we can see from the result mean(L,0). The resultant sequence -is the mean marks of all students that gave the exam for the five subjects. - -and :: - - mean(L,1) - - -is the average accumalative marks of individual students. Clearly, mean(L,0) -was a row wise calcultaion while mean(L,1) was a column wise calculation. - - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial. -we have learnt - - * How to do the standard statistical operations sum , mean - median and standard deviation in Python. - * Combine text loading and the statistical operation to solve - real world problems. - -{{{ 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 1 : - Internal Reviewer 2 : - External Reviewer : - diff -r d5248a15274c -r c77f7f5850dd statistics/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/statistics/questions.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,54 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. What is the function for calculating sum of a list? + + sum + +2. Calcutate the mean of the given list? + + student_marks=[74,78,56,87,91,82] + + mean(student_marks) + + +3. Given a two dimensional list,:: + two_dimensional_list=[[3,5,8,2,1],[4,3,6,2,1]] + + how do we calculate the mean of each row? + + + mean(two_dimensinal_list,1) + +4. What is the function for calculating standard deviation of a list? + + std + +5. Calcutate the median of the given list? + + student_marks=[74,78,56,87,91,82] + + median(age_list) + +6. How do you calculate median along the columns of two dimensional array? + + median(two_dimensional_list,0) + + +7. What is the name of the function to load text from an external file? + + loadtxt + +8. I have a file with 6 columns but I wish to load only text in column 2,3,4,5. How do I specify that? + + Using the parameter usecols=(2,3,4,5) + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Question 1 +2. Question 2 diff -r d5248a15274c -r c77f7f5850dd statistics/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/statistics/quickref.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd statistics/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/statistics/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,174 @@ +Hello friends and welcome to the tutorial on statistics using Python + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall learn + * Doing simple statistical operations in Python + * Applying these to real world problems + +You will need Ipython with pylab running on your computer +to use this tutorial. + +Also you will need to know about loading data using loadtxt to be +able to follow the real world application. + +We will first start with the most necessary statistical +operation i.e finding mean. + +We have a list of ages of a random group of people :: + + age_list=[4,45,23,34,34,38,65,42,32,7] + +One way of getting the mean could be getting sum of +all the elements and dividing by length of the list.:: + + sum_age_list =sum(age_list) + +sum function gives us the sum of the elements.:: + + mean_using_sum=float(sum_age_list)/len(age_list) + +This obviously gives the mean age but python has another +method for getting the mean. This is the mean function:: + + mean(age_list) + +Mean can be used in more ways in case of 2 dimensional lists. +Take a two dimensional list :: + + two_dimension=[[1,5,6,8],[1,3,4,5]] + +the mean function used in default manner will give the mean of the +flattened sequence. Flattened sequence means the two lists taken +as if it was a single list of elements :: + + mean(two_dimension) + flattened_seq=[1,5,6,8,1,3,4,5] + mean(flattened_seq) + +As you can see both the results are same. The other way is mean +of each column.:: + + mean(two_dimension,0) + array([ 1. , 4. , 5. , 6.5]) + +we pass an extra argument 0 in that case. + +In case of getting mean along the rows the argument is 1:: + + mean(two_dimension,1) + array([ 5. , 3.25]) + +We can see more option of mean using :: + + mean? + +Similarly we can calculate median and stanard deviation of a list +using the functions median and std:: + + median(age_list) + std(age_list) + +Median and std can also be calculated for two dimensional arrays along columns and rows just like mean. + + For example :: + + median(two_dimension,0) + std(two_dimension,1) + +This gives us the median along the colums and standard devition along the rows. + +Now lets apply this to a real world example + +We will a data file that is at the a path +``/home/fossee/sslc2.txt``.It contains record of students and their +performance in one of the State Secondary Board Examination. It has +180, 000 lines of record. We are going to read it and process this +data. We can see the content of file by double clicking on it. It +might take some time to open since it is quite a large file. Please +don't edit the data. This file has a particular structure. + +We can do :: + + cat /home/fossee/sslc2.txt + +to check the contents of the file. + +Each line in the file is a set of 11 fields separated +by semi-colons Consider a sample line from this file. +A;015163;JOSEPH RAJ S;083;042;47;00;72;244;;; + +The following are the fields in any given line. +* Region Code which is 'A' +* Roll Number 015163 +* Name JOSEPH RAJ S +* Marks of 5 subjects: ** English 083 ** Hindi 042 ** Maths 47 ** +Science AA (Absent) ** Social 72 +* Total marks 244 +* + +Now lets try and find the mean of English marks of all students. + +For this we do. :: + + L=loadtxt('/home/fossee/sslc2.txt',usecols=(3,),delimiter=';') + L + mean(L) + +loadtxt function loads data from an external file.Delimiter specifies +the kind of character are the fields of data seperated by. +usecols specifies the columns to be used so (3,). The 'comma' is added +because usecols is a sequence. + +To get the median marks. :: + + median(L) + +Standard deviation. :: + + std(L) + + +Now lets try and and get the mean for all the subjects :: + + L=loadtxt('/home/fossee/sslc2.txt',usecols=(3,4,5,6,7),delimiter=';') + mean(L,0) + array([ 73.55452504, 53.79828941, 62.83342759, 50.69806158, 63.17056881]) + +As we can see from the result mean(L,0). The resultant sequence +is the mean marks of all students that gave the exam for the five subjects. + +and :: + + mean(L,1) + + +is the average accumalative marks of individual students. Clearly, mean(L,0) +was a row wise calcultaion while mean(L,1) was a column wise calculation. + + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have learnt + + * How to do the standard statistical operations sum , mean + median and standard deviation in Python. + * Combine text loading and the statistical operation to solve + real world problems. + +{{{ 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 1 : + Internal Reviewer 2 : + External Reviewer : + diff -r d5248a15274c -r c77f7f5850dd statistics/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/statistics/slides.org Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,33 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\useoutertheme{infolines}\usecolortheme{default}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC +#+OPTIONS: H:5 num:t toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t + +#+TITLE: Statistics +#+AUTHOR: FOSSEE +#+DATE: 2010-09-14 Tue +#+EMAIL: info@fossee.in + +# \author[FOSSEE] {FOSSEE} + +# \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +# \date{} + +* Tutorial Plan +** Doing simple statistical operations in Python +** Using loadtxt to solve statistics problem + +* Summary +** seq=[1,5,6,8,1,3,4,5] +** sum(seq) +** mean(seq) +** median(seq) +** std(seq) + +* Summary + +** loadtxt diff -r d5248a15274c -r c77f7f5850dd statistics/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/statistics/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd symbolics.rst --- a/symbolics.rst Tue Oct 12 11:44:33 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,343 +0,0 @@ -Symbolics with Sage -------------------- - -This tutorial on using Sage for symbolic calculation is brought to you -by Fossee group. - -.. #[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 d5248a15274c -r c77f7f5850dd symbolics/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/symbolics/questions.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,53 @@ +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) + + +2. Question 2 diff -r d5248a15274c -r c77f7f5850dd symbolics/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/symbolics/quickref.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd symbolics/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/symbolics/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -0,0 +1,343 @@ +Symbolics with Sage +------------------- + +Hello friends and welcome to the 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 d5248a15274c -r c77f7f5850dd symbolics/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/symbolics/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd using python modules/script.rst --- a/using python modules/script.rst Tue Oct 12 11:44:33 2010 +0530 +++ b/using python modules/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -1,11 +1,27 @@ -.. 9.3 LO: using python modules (3) -.. --------------------------------- -.. * executing python scripts from command line -.. * import -.. * scipy -.. * pylab -.. * sys -.. * STDLIB modules show off +.. 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 : + External Reviewer : + Checklist OK? : [2010-10-05] + ==================== Using Python modules @@ -17,7 +33,8 @@ {{{ switch to next slide, outline slide }}} In this tutorial, we will see how to run python scripts from command -line, importing modules, importing scipy and pylab modules. +line, importing modules, importing scipy and pylab modules. And also +see the Python standard library. {{{ switch to next slide on executing python scripts from command line }}} @@ -48,6 +65,8 @@ {{{ open terminal and navigate to directory where hello.py was saved }}} +{{{ switch to next slide }}} + now run the Python script as, :: @@ -59,6 +78,8 @@ 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. @@ -87,6 +108,8 @@ 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 }}} :: @@ -100,6 +123,9 @@ 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 }}} :: @@ -115,6 +141,8 @@ 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 }}} :: @@ -130,29 +158,26 @@ 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, title, show - from pylab import xlim, ylim + 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 }}} -it could also be done as, - -.. 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) - Notice that we use ``scipy.pi`` instead of just ``pi`` as in the previous method, and the functions are called as ``pylab.plot()`` and @@ -211,7 +236,7 @@ The modules pylab, scipy, Mayavi are not part of the standard python library. -{{{ switch to next slide, recap }}} +{{{ 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 @@ -220,8 +245,3 @@ {{{ switch to next slide, thank you slide }}} Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: diff -r d5248a15274c -r c77f7f5850dd using python modules/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/slides.org Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd using python modules/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/slides.tex Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd using-sage/script.rst --- a/using-sage/script.rst Tue Oct 12 11:44:33 2010 +0530 +++ b/using-sage/script.rst Mon Oct 18 21:11:34 2010 +0530 @@ -1,10 +1,29 @@ -======== - Script -======== +.. 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 : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ {{{ show the welcome slide }}} -Welcome to this tutorial on using Sage. +Hello Friends. Welcome to this tutorial on using Sage. {{{ show the slide with outline }}} @@ -194,4 +213,8 @@ We have looked at some of the functions available for Linear Algebra, Calculus, Graph Theory and Number theory. -Thank You! +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 d5248a15274c -r c77f7f5850dd using-sage/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using-sage/slides.org Mon Oct 18 21:11:34 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 d5248a15274c -r c77f7f5850dd using-sage/slides.tex --- a/using-sage/slides.tex Tue Oct 12 11:44:33 2010 +0530 +++ b/using-sage/slides.tex Mon Oct 18 21:11:34 2010 +0530 @@ -1,95 +1,74 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{infolines} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} +% Created 2010-10-11 Mon 22:48 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{using Sage} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + \begin{frame} - \maketitle -\end{frame} +\frametitle{Outline} +\label{sec-1} -\begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} +\begin{itemize} +\item Calculus +\item Linear Algebra +\item Graph Theory +\item Number Theory +\end{itemize} \end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-2} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\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{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