# HG changeset patch # User Puneeth Chaganti # Date 1286517729 -19800 # Node ID 0ff3f1a97068fe28418414a79318fa28f587d195 # Parent 9bc78792904ba4558581583dc4dab16fb4a6fab0# Parent c507e9c413c6262b3b6d975afc3222a1514a4176 Merged heads. diff -r 9bc78792904b -r 0ff3f1a97068 additional_ipython.rst --- a/additional_ipython.rst Fri Oct 08 11:31:56 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,322 +0,0 @@ -.. Author : Nishanth - Internal Reviewer 1 : - Internal Reviewer 2 : - External Reviewer : - -.. Prerequisites: Embellinshing plots - -Script -====== - - -Hello friends and welcome to the tutorial on Additional Features of IPython - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall look at additional features of IPython that help us -to retreive the commands that we type on the interpreter and then save them -into a file and run it. - -Let us start ipython with pylab loaded, by typing -:: - - $ ipython -pylab - -on the terminal - -{{{ shit to terminal and type ipython -pylab }}} - -We shall first make a plot and then view the history and save it. -:: - - x = linspace(-2*pi, 2*pi, 100) - plot(x, xsinx(x)) - -xsin(x) is actually x * sin(x) -:: - - plot(x, x*sin(x)) - plot(x, sin(x)) - xlabel("x") - ylabel("$f(x)$") - title("x and xsin") - -We now have the plot. Let us look at the commands that we have typed in. The -history can be retreived by using =%hist= command. Type -:: - - %hist - -As you can see, it displays a list of recent commands that we typed. Every -command has a number in front, to specify in which order and when it was typed. - -Please note that there is a % sign before the hist command. This implies that -%hist is a command that is specific to IPython and not available in vannila -Python interpreter. These type of commands are called as magic commands. - -Also note that, the =%hist= itself is a command and is displayed as the most -recent command. This implies that anything we type in is stored as history, -irrespective of whether it is command or an error or IPython magic command. - -If we want only the recent 5 to be displayed, we pass the number as an argument -to =%hist= command. Hence -:: - - %hist 5 - -displays the recent 5 commands, inclusive of the =%hist= command. -The default number is 40. - -{{{ Pause here and try out the following exercises }}} - -%% 1 %% Read through the %hist documenatation and find out how can we list all - the commands between 5 and 10 - -{{{ continue from paused state }}} - -As we can see from =%hist= documentation, -:: - - %hist 5 10 - -displays the commands from 5 to 10 - -Now that we have the history, we would like to save the required line of code -from history. This is possible by using the =%save= command. - -Before we do that, let us first look at history and identify what lines of code -we require.Type -:: - - %hist - - -{{{ point to the lines }}} - -The first command is linspace. But second command is a command that gave us an -error. Hence we do not need seconf. The commands from third to sixth are -required. The seventh command although is correct, we do not need it since we -are setting the title correctly in the eigthth command. - -So we need first third to sixth and the eigthth command for our program. -Hence the syntax of =%save= is -:: - - %save /home/fossee/plot_script.py 1 3-6 8 - -{{{ point to the output of the command }}} - -The command saves first and then third to sixth and eighth lines of code into -the specified file. - -The first argument to %save is the path of file to save the commands and the -arguments there after are the commands to be saved in the given order. - -{{{ goto the file and open it and show it }}} - -{{{ Pause here and try out the following exercises }}} - -%% 2 %% change the label on y-axis to "y" and save the lines of code - accordingly - -{{{ continue from paused state }}} - -we use the command =ylabel= on interpreter as -:: - - ylabel("y") - -and then do -:: - - %save /home/fossee/example_plot.py 1 3-6 10 - -Now that we have the required lines of code in a file, let us learn how to run -the file as a python script. - -We use the IPython magic command =%run= to do this. Type -:: - - %run -i /home/fossee/plot_script.py - -The script runs but we do not see the plot. This happens because we are running -a script and we are not in interactive mode anymore. - -Hence on your terminal type -:: - - show() - -to show the plot. - -{{{ Pause here and try out the following exercises }}} - -%% 3 %% Use %hist and %save and create a script that has show in it and run it - to produce and show the plot. - -{{{ continue from paused state }}} - -We first look at the history using -:: - - %hist 20 - -Then save the script using -:: - - %save /home/fossee/show_included.py 1 3-6 8 10 13 - %run -i /home/fossee/show_included.py - -We get the desired plot. - -The reason for including a -i after run is to tell the interpreter that if any -name is not found in script, search for it in the interpreter. Hence all these -sin, plot, pi and show which are not available in script, are taken from the -interpreter and used to run the script. - -{{{ Pause here and try out the following exercises }}} - -%% 4 %% Run the script without using the -i option. Do you find any difference? - -{{{ continue from paused state }}} - -We see that it raises nameerror saying the name linspace is not found. - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial. -we have looked at - - * Retreiving history using =%hist= command - * Vieweing only a part of history by passing an argument to %hist - * saving the required lines of code in required order using %save - * using %run -i command to run the saved script - -{{{ Show the "sponsored by FOSSEE" slide }}} - -#[Nishanth]: Will add this line after all of us fix on one. -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thankyou - -Questions -========= - - 1. How do you retrieve the recent 5 commands - - a. ``%hist`` - #. ``%hist -5`` - #. ``%hist 5`` - #. ``%hist 5-10`` - - Answer: ``%hist 5`` - - 2. If there were 20 commands typed and ``%hist`` is used. How many commands - will be displayed. - - a. 10 - #. 20 - #. 21 - #. 19 - - Answer: 21 - - 3. is ``%hist`` considered as a command - - a. True - #. False - - Answer: True - - 4. how do you retreive the commands from 20 to 50 (inclusive of 20 and 50) - - a. ``%hist 20 50`` - #. ``%hist 19 50`` - #. ``%hist 19 51`` - #. ``%hist 21 50`` - - Answer: ``%hist 20 50`` - - 5. What does the ``%hist 2 5 7`` command do - - a. lists the second, fifth and seventh commands - #. lists the commands from 2 to 5 and the seventh command - #. raises an error - #. lists the commands 2 to 7 - - Answer: raises an error - - 6. How many commands are displayed when lot of coomands were typed and - ``%hist`` is used. - - a. 20 - #. 10 - #. 50 - #. 40 - - Answer: 40 - - 7. How do you save the lines 2 3 4 5 7 9 10 11 - - a. ``%save filepath 2-5 7 9-11`` - #. ``%save filepath 2-11`` - #. ``%save filepath`` - #. ``%save 2-5 7 9 10 11`` - - Answer: ``%save filepath 2-5 7 9-11`` - - 8. You are working in /home/user. Where is the file saved when you do - ``%save hello.py 1-3`` - - a. /home/user/hello.py - #. /hello.py - #. /home/hello.py - #. /home/user/ipython/hello.py - - Answer: /home/user/hello.py - - 9. Which lines are saved by the command ``%save filepath 2-5 7 1`` and in - which order - - a. 2 3 4 5 7 1 - #. 1 2 3 4 5 6 7 - #. 2 5 7 1 - #. 1 2 5 7 - - 10. What happens when ``%save filepath line_numbers`` is used and a file - already exists in that path. - - a. It is overwritten - #. The commands are added to the file - #. It raises an error - #. A prompt to confirm overwriting is displayed - - Answer: A prompt to confirm overwriting is displayed - - 11. Read through the documentation of ``%hist`` and find its alternative name - - Answer: ``%history`` - - 12. Are ``%run /home/user/saved.py`` and ``%run /home/user/saved`` the same - - a. Yes - #. No - - Answer: Yes - - 13. The file hello.py contains only one command ``x = x + 1``. What happens - when you do ``%run hello.py`` - - Answer: Raises a nameerror - - 14. The file hello.py contains only one command ``x = x + 1``. If value of x - is 5 and what does ``%run -i hello.py`` do. - - a. raises an error - #. increments value of x by 1 - #. Does nothing - - Answer: increments the value of x by 1 diff -r 9bc78792904b -r 0ff3f1a97068 additional_ipython/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_ipython/questions.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,118 @@ +Objective Questions +------------------- + + 1. How do you retrieve the recent 5 commands + + a. ``%hist`` + #. ``%hist -5`` + #. ``%hist 5`` + #. ``%hist 5-10`` + + Answer: ``%hist 5`` + + 2. If there were 20 commands typed and ``%hist`` is used. How many commands + will be displayed. + + a. 10 + #. 20 + #. 21 + #. 19 + + Answer: 21 + + 3. is ``%hist`` considered as a command + + a. True + #. False + + Answer: True + + 4. how do you retreive the commands from 20 to 50 (inclusive of 20 and 50) + + a. ``%hist 20 50`` + #. ``%hist 19 50`` + #. ``%hist 19 51`` + #. ``%hist 21 50`` + + Answer: ``%hist 20 50`` + + 5. What does the ``%hist 2 5 7`` command do + + a. lists the second, fifth and seventh commands + #. lists the commands from 2 to 5 and the seventh command + #. raises an error + #. lists the commands 2 to 7 + + Answer: raises an error + + 6. How many commands are displayed when lot of coomands were typed and + ``%hist`` is used. + + a. 20 + #. 10 + #. 50 + #. 40 + + Answer: 40 + + 7. How do you save the lines 2 3 4 5 7 9 10 11 + + a. ``%save filepath 2-5 7 9-11`` + #. ``%save filepath 2-11`` + #. ``%save filepath`` + #. ``%save 2-5 7 9 10 11`` + + Answer: ``%save filepath 2-5 7 9-11`` + + 8. You are working in /home/user. Where is the file saved when you do + ``%save hello.py 1-3`` + + a. /home/user/hello.py + #. /hello.py + #. /home/hello.py + #. /home/user/ipython/hello.py + + Answer: /home/user/hello.py + + 9. Which lines are saved by the command ``%save filepath 2-5 7 1`` and in + which order + + a. 2 3 4 5 7 1 + #. 1 2 3 4 5 6 7 + #. 2 5 7 1 + #. 1 2 5 7 + + 10. What happens when ``%save filepath line_numbers`` is used and a file + already exists in that path. + + a. It is overwritten + #. The commands are added to the file + #. It raises an error + #. A prompt to confirm overwriting is displayed + + Answer: A prompt to confirm overwriting is displayed + + 11. Read through the documentation of ``%hist`` and find its alternative name + + Answer: ``%history`` + + 12. Are ``%run /home/user/saved.py`` and ``%run /home/user/saved`` the same + + a. Yes + #. No + + Answer: Yes + + 13. The file hello.py contains only one command ``x = x + 1``. What happens + when you do ``%run hello.py`` + + Answer: Raises a nameerror + + 14. The file hello.py contains only one command ``x = x + 1``. If value of x + is 5 and what does ``%run -i hello.py`` do. + + a. raises an error + #. increments value of x by 1 + #. Does nothing + + Answer: increments the value of x by 1 diff -r 9bc78792904b -r 0ff3f1a97068 additional_ipython/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_ipython/quickref.tex Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,11 @@ +Creating a tuple:\\ +{\ex \lstinline| t = (1, "hello", 2.5)|} + +Accessing elements of tuples:\\ +{\ex \lstinline| t[index] Ex: t[2]|} + +Accessing slices of tuples:\\ +{\ex \lstinline| t[start:stop:step]|} + +Swapping values:\\ +{\ex \lstinline| a, b = b, a|} diff -r 9bc78792904b -r 0ff3f1a97068 additional_ipython/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_ipython/script.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,214 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - + C - + D - + +.. Prerequisites +.. ------------- + +.. 1. Embellishing Plots + +.. Author : Nishanth Amuluru + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +Hello friends and welcome to the tutorial on Additional Features of IPython + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall look at additional features of IPython that help us +to retreive the commands that we type on the interpreter and then save them +into a file and run it. + +Let us start ipython with pylab loaded, by typing +:: + + $ ipython -pylab + +on the terminal + +{{{ shit to terminal and type ipython -pylab }}} + +We shall first make a plot and then view the history and save it. +:: + + x = linspace(-2*pi, 2*pi, 100) + plot(x, xsinx(x)) + +xsin(x) is actually x * sin(x) +:: + + plot(x, x*sin(x)) + plot(x, sin(x)) + xlabel("x") + ylabel("$f(x)$") + title("x and xsin") + +We now have the plot. Let us look at the commands that we have typed in. The +history can be retreived by using =%hist= command. Type +:: + + %hist + +As you can see, it displays a list of recent commands that we typed. Every +command has a number in front, to specify in which order and when it was typed. + +Please note that there is a % sign before the hist command. This implies that +%hist is a command that is specific to IPython and not available in vannila +Python interpreter. These type of commands are called as magic commands. + +Also note that, the =%hist= itself is a command and is displayed as the most +recent command. This implies that anything we type in is stored as history, +irrespective of whether it is command or an error or IPython magic command. + +If we want only the recent 5 to be displayed, we pass the number as an argument +to =%hist= command. Hence +:: + + %hist 5 + +displays the recent 5 commands, inclusive of the =%hist= command. +The default number is 40. + +{{{ Pause here and try out the following exercises }}} + +%% 1 %% Read through the %hist documenatation and find out how can we list all + the commands between 5 and 10 + +{{{ continue from paused state }}} + +As we can see from =%hist= documentation, +:: + + %hist 5 10 + +displays the commands from 5 to 10 + +Now that we have the history, we would like to save the required line of code +from history. This is possible by using the =%save= command. + +Before we do that, let us first look at history and identify what lines of code +we require.Type +:: + + %hist + + +{{{ point to the lines }}} + +The first command is linspace. But second command is a command that gave us an +error. Hence we do not need seconf. The commands from third to sixth are +required. The seventh command although is correct, we do not need it since we +are setting the title correctly in the eigthth command. + +So we need first third to sixth and the eigthth command for our program. +Hence the syntax of =%save= is +:: + + %save /home/fossee/plot_script.py 1 3-6 8 + +{{{ point to the output of the command }}} + +The command saves first and then third to sixth and eighth lines of code into +the specified file. + +The first argument to %save is the path of file to save the commands and the +arguments there after are the commands to be saved in the given order. + +{{{ goto the file and open it and show it }}} + +{{{ Pause here and try out the following exercises }}} + +%% 2 %% change the label on y-axis to "y" and save the lines of code + accordingly + +{{{ continue from paused state }}} + +we use the command =ylabel= on interpreter as +:: + + ylabel("y") + +and then do +:: + + %save /home/fossee/example_plot.py 1 3-6 10 + +Now that we have the required lines of code in a file, let us learn how to run +the file as a python script. + +We use the IPython magic command =%run= to do this. Type +:: + + %run -i /home/fossee/plot_script.py + +The script runs but we do not see the plot. This happens because we are running +a script and we are not in interactive mode anymore. + +Hence on your terminal type +:: + + show() + +to show the plot. + +{{{ Pause here and try out the following exercises }}} + +%% 3 %% Use %hist and %save and create a script that has show in it and run it + to produce and show the plot. + +{{{ continue from paused state }}} + +We first look at the history using +:: + + %hist 20 + +Then save the script using +:: + + %save /home/fossee/show_included.py 1 3-6 8 10 13 + %run -i /home/fossee/show_included.py + +We get the desired plot. + +The reason for including a -i after run is to tell the interpreter that if any +name is not found in script, search for it in the interpreter. Hence all these +sin, plot, pi and show which are not available in script, are taken from the +interpreter and used to run the script. + +{{{ Pause here and try out the following exercises }}} + +%% 4 %% Run the script without using the -i option. Do you find any difference? + +{{{ continue from paused state }}} + +We see that it raises nameerror saying the name linspace is not found. + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have looked at + + * Retreiving history using =%hist= command + * Vieweing only a part of history by passing an argument to %hist + * saving the required lines of code in required order using %save + * using %run -i command to run the saved script + +{{{ Show the "sponsored by FOSSEE" slide }}} + +#[Nishanth]: Will add this line after all of us fix on one. +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thankyou + diff -r 9bc78792904b -r 0ff3f1a97068 additional_ipython/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_ipython/slides.tex Fri Oct 08 11:32:09 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 9bc78792904b -r 0ff3f1a97068 embellishing_a_plot.rst --- a/embellishing_a_plot.rst Fri Oct 08 11:31:56 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,446 +0,0 @@ -.. Author : Nishanth - Internal Reviewer 1 : Anoop - Internal Reviewer 2 : Madhu - External Reviewer : - -.. Prerequisites: using ``plot`` command - -Hello friends and welcome to the tutorial on Embellishing Plots. - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline }}} - -In this tutorial, we shall look at how to modify the colour, thickness and -linestyle of the plot. We shall then learn how to add title to the plot and -then look at adding labels to x and y axes. we shall also look at adding -annotations to the plot and setting the limits of axes. - -Let us start ipython with pylab loaded, by typing on the terminal - -{{{ shift to terminal and type ipython -pylab }}} - -:: - - ipython -pylab - -.. #[madhu: I feel the instructions should precede the actual action, - -since while recording we need to know before hand what we need to do] - -We shall first make a simple plot and start decorating it. - -.. #[madhu: start decorating it should be fine, with is not necessary] - -:: - - x = linspace(-2, 4, 20) - plot(x, sin(x)) - -.. #[madhu: Standard is to choose between -50 to 50 or 0 to 50 with 100 - points right?] - -As we can see, the default colour and the default thickness of the -line is as decided by pylab. Wouldn't be nice if we could control -these parameters in the plot? This is possible by passing additional -arguments to the plot command. - -.. #[[Anoop: I think it will be good to rephrase the sentence]] -.. #[madhu: Why "you" here? Shouldn't this be "we" as decided? Also I - added "the default" check the diff] - -The additional argument that we shall be passing in here now is the -colour argument. We shall first clear the figure and plot the same in -red colour. Hence - -.. #[Madhu: Note the diff for changes] - :: - - clf() - plot(x, sin(x), 'r') - -As we can see we have the same plot but now in red colour. - -.. #[Madhu: diff again] - -To alter the thickness of the line, we use the ``linewidth`` argument in the plot -command. Hence -:: - - plot(x, cos(x), linewidth=2) - -produces a plot with a thicker line, to be more precise plot with line -thickness 2. - -.. #[[Anoop: I guess it will be good if you say that it affects the - same plot, as you have not cleared the figure]] -.. #[Madhu: To Anoop, not necessary I feel since they can see it?] - -{{{ Show the plot and compare the sine and cos plots }}} - -{{{ Pause here and try out the following exercises }}} - -.. #[[Anoop: is the above a context switch for the person who does the - recording, other wise if it an instruction to the person viewing - the video, then I guess the three braces can be removed.]] - -%% 1 %% Plot sin(x) in blue colour and with linewidth as 3 - -{{{ continue from paused state }}} - -A combination of colour and linewidth would do the job for us. Hence -:: - - clf() - plot(x, sin(x), 'b', linewidth=3) - -.. #[[Anoop: add clf()]] - -produces the required plot - -.. #[Nishanth]: I could not think of a SIMPLE recipe approach for - introducing linestyle. Hence the naive approach. - -.. #[[Anoop: I guess the recipe is fine, but would be better if you - add the problem statement rather than just saying "let's do a simple - plot"]] - -.. #[Madhu: It is good enough.] - -Occasionally we would also want to alter the style of line. Sometimes -all we want is just a bunch of points not joined. This is possible by -passing the linestyle argument along with or instead of the colour -argument. Hence :: - - clf() - plot(x, sin(x), '.') - -produces a plot with only points. - -To produce the same plot but now in blue colour, we do -:: - - clf() - plot(x, sin(x), 'b.') - -Other available options can be seen in the documentation of plot. -:: - - plot? - -{{{ Run through the documentation and show the options available }}} - -{{{ Show the options available for line style and colors }}} - -.. #[Madhu: The script needs to tell what needs to be shown or - explained.] - -{{{ Pause here and try out the following exercises }}} - -.. #[[Anoop: same question as above, should it be read out?]] - -%% 2 %% Plot the sine curve with green filled circles. - -{{{ continue from paused state }}} - -All we have to do is use a combination of linestyle and colour to acheive this. -Hence -:: - - clf() - plot(x, cos(x), 'go') - -produces the required plot. - -{{{ Pause here and try out the following exercises }}} - -%% 3 %% Plot the curve of x vs tan(x) in red dashed line and linewidth 3 - -{{{ continue from paused state }}} - -.. #[Madhu: I did not understand the question] - -Now that we know how to produce a bare minimum plot with colour, style -and thickness of our interest, we shall look at decorating the plot. - -Let us start with a plot of the function -x^2 + 4x - 5. -:: - - plot(x, -x*x + 4*x - 5, 'r', linewidth=2) - -{{{ Show the plot window and switch back to terminal }}} - -We now have the plot in a colour and linewidth of our interest. As you can see, -the figure does not have any description describing the plot. - -.. #[Madhu: Added "not". See the diff] - -We will now add a title to the plot by using the ``title`` command. -:: - - title("Parabolic function -x^2+4x-5") - -{{{ Show the plot window and point to the title }}} - -The figure now has a title which describes what the plot is. The -``title`` command as you can see, takes a string as an argument and sets -the title accordingly. - -.. #[Madhu: See the diff] - -The formatting in title is messed and it does not look clean. You can imagine -what would be the situation if there were fractions and more complex functions -like log and exp. Wouldn't it be good if there was LaTex like formatting? - -That is also possible by adding a $ sign before and after the part of the -string that should be in LaTex style. - -for instance, we can use -:: - - title("Parabolic function $-x^2+4x-5$") - -and we get the polynomial formatted properly. - -.. #[Nishanth]: Unsure if I have to give this exercise since enclosing the whole - string in LaTex style is not good - -.. #[[Anoop: I guess you can go ahead with the LaTex thing, it's - cool!]] -.. #[Madhu: Instead of saying LaTeX style you can say Typeset math - since that is how it is called as. I am not sure as well. It - doesn't really solve the purpose] - -{{{ Pause here and try out the following exercises }}} - -%% 4 %% Change the title of the figure such that the whole title is formatted - in LaTex style - -{{{ continue from the paused state }}} - -The solution is to enclose the whole string in between $. Hence, -:: - - title("$Parabolic function -x^2+4x-5$") - -gives a title that looks neatly formatted. - -Although we have title, the plot is not complete without labelling x -and y axes. Hence we shall label x-axis to "x" and y-axis to "f(x)" :: - - xlabel("x") - -{{{ Switch to plot window and show the xlabel }}} - -As you can see, ``xlabel`` command takes a string as an argument, -similar to the ``title`` command and sets it as the label to x-axis. - -.. #[See the diff] - -Similarly, -:: - - ylabel("f(x)") - -sets the name of the y-axis as "f(x)" - -{{{ Show the plot window and point to ylabel and switch back to the terminal }}} - -{{{ Pause here and try out the following exercises }}} - -%% 5 %% Set the x and y labels as "x" and "f(x)" in LaTex style. - -{{{ continue from paused state }}} - -Since we need LaTex style formatting, all we have to do is enclose the string -in between two $. Hence, -:: - - xlabel("$x$") - yalbel("$f(x)$") - -does the job for us. - -{{{ Show the plot window with clean labels }}} - -The plot is now almost complete. Except that we have still not seen how to -name the points. For example the point (2, -1) is the local maxima. We would -like to name the point accordingly. We can do this by using -:: - - annotate("local maxima", xy=(2, -1)) - -{{{ Show the annotation that has appeared on the plot }}} - -As you can see, the first argument to ``annotate`` command is the name we would -like to mark the point as and the second argument is the co-ordinates of the -point at which the name should appear. It is a sequence containing two numbers. -The first is x co-ordinate and second is y co-ordinate. - -.. #[[Anoop: I think we should tell explicitely that xy takes a - sequence or a tuple]] -.. #[Madhu: Agreed to what anoop says and also that xy= is the point - part should be rephrased I think.] - -{{{ Pause here and try out the following exercises }}} - -%% 6 %% Make an annotation called "root" at the point (-4, 0) - What happens to the first annotation ? - -{{{ continue from paused state }}} - -As we can see, every annotate command makes a new annotation on the figure. - -Now we have everything we need to decorate a plot. but the plot would be -incomplete if we can not set the limits of axes. This is possible using the -button on the plot window. - -we shall look at how to get and set them from the script. -:: - - xlim() - ylim() - -We see that ``xlim`` function returns the current x axis limits and ylim -function returns the current y-axis limits. - -Let us look at how to set the limits. -:: - - xlim(-4, 5) - -We see the limits of x-axis are now set to -4 and 5. -Similarly -:: - - ylim(-15, 2) - -sets the limits of y-axis appropriately. - -{{{ Pause here and try out the following exercises }}} - -%% 7 %% Set the limits of axes such that the area of interest is the rectangle - (-1, -15) and (3, 0) - -{{{ continue from paused state }}} - -As we can see, the lower upper limits of x-axis in the question are -1 and 3. -The limits of y-axis are -15 and 0. - -:: - - xlim(-1, 3) - ylim(-15, 0) - -Gives us the required rectangle. - -{{{ Show summary slide }}} - -we have looked at - - * Modifying the attributes of plot by passing additional arguments - * How to add title - * How to incorporate LaTex style formatting - * How to label x and y axes - * How to add annotations - * How to set the limits of axes - -{{{ Show the "sponsored by FOSSEE" slide }}} - -.. #[Nishanth]: Will add this line after all of us fix on one. - -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thankyou - -Questions -========= - - 1. Draw a plot of cosine graph between -2pi to 2pi with line thickness 4 - - Answer:: - - x = linspace(-2*pi, 2*pi) - plot(x, cos(x), linewidth=4) - - 2. Draw a plot of the polynomial x^2-5x+6 in the range 0 to 5 in blue dotted - line - - Answer:: - - x = linspace(-2*pi, 2*pi) - plot(x, x**2 - 5*x + 6, 'r.') - - 3. Which marker is used to get circles - - a. '.' - #. '^' - #. 'o' - #. '--' - - 4. What does the '^' marker produce - - Answer: Triangle up marker - - 5. How do you set the title as x^2-5x+6 in LaTex style formatting - - Answer: title("$x^2-5x+6$") - -6. What happens when the following code is executed:: - - xlabel("First label") - xlabel("Second label") - - Answer: The label of x-axis is set to "Second label" - - 7. Read thorugh the documentation and find out is there a way to modify the - alignment of text in the command ``ylabel`` - - a. Yes - #. No - - Answer: No - - 8. How to add the annotation "Maxima" at the point (1, 2) - - Answer: annotate("Maxima", xy=(1, 2)) - - 9. Is the command ``annotate("max", (1, 2))`` same as ``annotate("max", - xy=(1, 2)`` - - a. True - b. False - - Answer: True - - 10. When a new annotation is made at a point, what happens to the old one - - a. It is replaced - b. It is overwritten - c. The new annotation is combined with old one - - Answer: It is overwritten - - 11. What happens when xlim is used without arguments - - Answer: It gives the current limits of x-axis - - 12. What happens when ``ylim(0, 5)`` is used - - Answer: It sets the lower and upper limits of y-axis to 0 and 5 - - 13. Draw a cosine plot from 0 to 2*pi with green dots. annotate the origin as - "origin" and set x and y labels to "x" and cos(x) and x limits to 0 and - 2pi and y limits to -1.2 and 1.2 - - Answer:: - - x = linspace(0, 2*pi) - plot(x, cos(x), 'g.') - annotate("origin", (0, 0)) - xlabel("$x$") - ylabel("$cos(x)$") - xlim(0, 2*pi) - ylim(-1.2, 1.2) - diff -r 9bc78792904b -r 0ff3f1a97068 embellishing_a_plot/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/embellishing_a_plot/questions.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,90 @@ +Objective Questions +------------------- + + 1. Draw a plot of cosine graph between -2pi to 2pi with line thickness 4 + + Answer:: + + x = linspace(-2*pi, 2*pi) + plot(x, cos(x), linewidth=4) + + 2. Draw a plot of the polynomial x^2-5x+6 in the range 0 to 5 in blue dotted + line + + Answer:: + + x = linspace(-2*pi, 2*pi) + plot(x, x**2 - 5*x + 6, 'r.') + + 3. Which marker is used to get circles + + a. '.' + #. '^' + #. 'o' + #. '--' + + 4. What does the '^' marker produce + + Answer: Triangle up marker + + 5. How do you set the title as x^2-5x+6 in LaTex style formatting + + Answer: title("$x^2-5x+6$") + +6. What happens when the following code is executed:: + + xlabel("First label") + xlabel("Second label") + + Answer: The label of x-axis is set to "Second label" + + 7. Read thorugh the documentation and find out is there a way to modify the + alignment of text in the command ``ylabel`` + + a. Yes + #. No + + Answer: No + + 8. How to add the annotation "Maxima" at the point (1, 2) + + Answer: annotate("Maxima", xy=(1, 2)) + + 9. Is the command ``annotate("max", (1, 2))`` same as ``annotate("max", + xy=(1, 2)`` + + a. True + b. False + + Answer: True + + 10. When a new annotation is made at a point, what happens to the old one + + a. It is replaced + b. It is overwritten + c. The new annotation is combined with old one + + Answer: It is overwritten + + 11. What happens when xlim is used without arguments + + Answer: It gives the current limits of x-axis + + 12. What happens when ``ylim(0, 5)`` is used + + Answer: It sets the lower and upper limits of y-axis to 0 and 5 + + 13. Draw a cosine plot from 0 to 2*pi with green dots. annotate the origin as + "origin" and set x and y labels to "x" and cos(x) and x limits to 0 and + 2pi and y limits to -1.2 and 1.2 + + Answer:: + + x = linspace(0, 2*pi) + plot(x, cos(x), 'g.') + annotate("origin", (0, 0)) + xlabel("$x$") + ylabel("$cos(x)$") + xlim(0, 2*pi) + ylim(-1.2, 1.2) + diff -r 9bc78792904b -r 0ff3f1a97068 embellishing_a_plot/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/embellishing_a_plot/quickref.tex Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,11 @@ +Creating a tuple:\\ +{\ex \lstinline| t = (1, "hello", 2.5)|} + +Accessing elements of tuples:\\ +{\ex \lstinline| t[index] Ex: t[2]|} + +Accessing slices of tuples:\\ +{\ex \lstinline| t[start:stop:step]|} + +Swapping values:\\ +{\ex \lstinline| a, b = b, a|} diff -r 9bc78792904b -r 0ff3f1a97068 embellishing_a_plot/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/embellishing_a_plot/script.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,371 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - + C - + D - + +.. Prerequisites +.. ------------- + +.. 1. Using the ``plot`` command interactively + +.. Author : Nishanth Amuluru + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +Hello friends and welcome to the tutorial on Embellishing Plots. + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline }}} + +In this tutorial, we shall look at how to modify the colour, thickness and +linestyle of the plot. We shall then learn how to add title to the plot and +then look at adding labels to x and y axes. we shall also look at adding +annotations to the plot and setting the limits of axes. + +Let us start ipython with pylab loaded, by typing on the terminal + +{{{ shift to terminal and type ipython -pylab }}} + +:: + + ipython -pylab + +.. #[madhu: I feel the instructions should precede the actual action, + +since while recording we need to know before hand what we need to do] + +We shall first make a simple plot and start decorating it. + +.. #[madhu: start decorating it should be fine, with is not necessary] + +:: + + x = linspace(-2, 4, 20) + plot(x, sin(x)) + +.. #[madhu: Standard is to choose between -50 to 50 or 0 to 50 with 100 + points right?] + +As we can see, the default colour and the default thickness of the +line is as decided by pylab. Wouldn't be nice if we could control +these parameters in the plot? This is possible by passing additional +arguments to the plot command. + +.. #[[Anoop: I think it will be good to rephrase the sentence]] +.. #[madhu: Why "you" here? Shouldn't this be "we" as decided? Also I + added "the default" check the diff] + +The additional argument that we shall be passing in here now is the +colour argument. We shall first clear the figure and plot the same in +red colour. Hence + +.. #[Madhu: Note the diff for changes] + :: + + clf() + plot(x, sin(x), 'r') + +As we can see we have the same plot but now in red colour. + +.. #[Madhu: diff again] + +To alter the thickness of the line, we use the ``linewidth`` argument in the plot +command. Hence +:: + + plot(x, cos(x), linewidth=2) + +produces a plot with a thicker line, to be more precise plot with line +thickness 2. + +.. #[[Anoop: I guess it will be good if you say that it affects the + same plot, as you have not cleared the figure]] +.. #[Madhu: To Anoop, not necessary I feel since they can see it?] + +{{{ Show the plot and compare the sine and cos plots }}} + +{{{ Pause here and try out the following exercises }}} + +.. #[[Anoop: is the above a context switch for the person who does the + recording, other wise if it an instruction to the person viewing + the video, then I guess the three braces can be removed.]] + +%% 1 %% Plot sin(x) in blue colour and with linewidth as 3 + +{{{ continue from paused state }}} + +A combination of colour and linewidth would do the job for us. Hence +:: + + clf() + plot(x, sin(x), 'b', linewidth=3) + +.. #[[Anoop: add clf()]] + +produces the required plot + +.. #[Nishanth]: I could not think of a SIMPLE recipe approach for + introducing linestyle. Hence the naive approach. + +.. #[[Anoop: I guess the recipe is fine, but would be better if you + add the problem statement rather than just saying "let's do a simple + plot"]] + +.. #[Madhu: It is good enough.] + +Occasionally we would also want to alter the style of line. Sometimes +all we want is just a bunch of points not joined. This is possible by +passing the linestyle argument along with or instead of the colour +argument. Hence :: + + clf() + plot(x, sin(x), '.') + +produces a plot with only points. + +To produce the same plot but now in blue colour, we do +:: + + clf() + plot(x, sin(x), 'b.') + +Other available options can be seen in the documentation of plot. +:: + + plot? + +{{{ Run through the documentation and show the options available }}} + +{{{ Show the options available for line style and colors }}} + +.. #[Madhu: The script needs to tell what needs to be shown or + explained.] + +{{{ Pause here and try out the following exercises }}} + +.. #[[Anoop: same question as above, should it be read out?]] + +%% 2 %% Plot the sine curve with green filled circles. + +{{{ continue from paused state }}} + +All we have to do is use a combination of linestyle and colour to acheive this. +Hence +:: + + clf() + plot(x, cos(x), 'go') + +produces the required plot. + +{{{ Pause here and try out the following exercises }}} + +%% 3 %% Plot the curve of x vs tan(x) in red dashed line and linewidth 3 + +{{{ continue from paused state }}} + +.. #[Madhu: I did not understand the question] + +Now that we know how to produce a bare minimum plot with colour, style +and thickness of our interest, we shall look at decorating the plot. + +Let us start with a plot of the function -x^2 + 4x - 5. +:: + + plot(x, -x*x + 4*x - 5, 'r', linewidth=2) + +{{{ Show the plot window and switch back to terminal }}} + +We now have the plot in a colour and linewidth of our interest. As you can see, +the figure does not have any description describing the plot. + +.. #[Madhu: Added "not". See the diff] + +We will now add a title to the plot by using the ``title`` command. +:: + + title("Parabolic function -x^2+4x-5") + +{{{ Show the plot window and point to the title }}} + +The figure now has a title which describes what the plot is. The +``title`` command as you can see, takes a string as an argument and sets +the title accordingly. + +.. #[Madhu: See the diff] + +The formatting in title is messed and it does not look clean. You can imagine +what would be the situation if there were fractions and more complex functions +like log and exp. Wouldn't it be good if there was LaTex like formatting? + +That is also possible by adding a $ sign before and after the part of the +string that should be in LaTex style. + +for instance, we can use +:: + + title("Parabolic function $-x^2+4x-5$") + +and we get the polynomial formatted properly. + +.. #[Nishanth]: Unsure if I have to give this exercise since enclosing the whole + string in LaTex style is not good + +.. #[[Anoop: I guess you can go ahead with the LaTex thing, it's + cool!]] +.. #[Madhu: Instead of saying LaTeX style you can say Typeset math + since that is how it is called as. I am not sure as well. It + doesn't really solve the purpose] + +{{{ Pause here and try out the following exercises }}} + +%% 4 %% Change the title of the figure such that the whole title is formatted + in LaTex style + +{{{ continue from the paused state }}} + +The solution is to enclose the whole string in between $. Hence, +:: + + title("$Parabolic function -x^2+4x-5$") + +gives a title that looks neatly formatted. + +Although we have title, the plot is not complete without labelling x +and y axes. Hence we shall label x-axis to "x" and y-axis to "f(x)" :: + + xlabel("x") + +{{{ Switch to plot window and show the xlabel }}} + +As you can see, ``xlabel`` command takes a string as an argument, +similar to the ``title`` command and sets it as the label to x-axis. + +.. #[See the diff] + +Similarly, +:: + + ylabel("f(x)") + +sets the name of the y-axis as "f(x)" + +{{{ Show the plot window and point to ylabel and switch back to the terminal }}} + +{{{ Pause here and try out the following exercises }}} + +%% 5 %% Set the x and y labels as "x" and "f(x)" in LaTex style. + +{{{ continue from paused state }}} + +Since we need LaTex style formatting, all we have to do is enclose the string +in between two $. Hence, +:: + + xlabel("$x$") + yalbel("$f(x)$") + +does the job for us. + +{{{ Show the plot window with clean labels }}} + +The plot is now almost complete. Except that we have still not seen how to +name the points. For example the point (2, -1) is the local maxima. We would +like to name the point accordingly. We can do this by using +:: + + annotate("local maxima", xy=(2, -1)) + +{{{ Show the annotation that has appeared on the plot }}} + +As you can see, the first argument to ``annotate`` command is the name we would +like to mark the point as and the second argument is the co-ordinates of the +point at which the name should appear. It is a sequence containing two numbers. +The first is x co-ordinate and second is y co-ordinate. + +.. #[[Anoop: I think we should tell explicitely that xy takes a + sequence or a tuple]] +.. #[Madhu: Agreed to what anoop says and also that xy= is the point + part should be rephrased I think.] + +{{{ Pause here and try out the following exercises }}} + +%% 6 %% Make an annotation called "root" at the point (-4, 0) + What happens to the first annotation ? + +{{{ continue from paused state }}} + +As we can see, every annotate command makes a new annotation on the figure. + +Now we have everything we need to decorate a plot. but the plot would be +incomplete if we can not set the limits of axes. This is possible using the +button on the plot window. + +we shall look at how to get and set them from the script. +:: + + xlim() + ylim() + +We see that ``xlim`` function returns the current x axis limits and ylim +function returns the current y-axis limits. + +Let us look at how to set the limits. +:: + + xlim(-4, 5) + +We see the limits of x-axis are now set to -4 and 5. +Similarly +:: + + ylim(-15, 2) + +sets the limits of y-axis appropriately. + +{{{ Pause here and try out the following exercises }}} + +%% 7 %% Set the limits of axes such that the area of interest is the rectangle + (-1, -15) and (3, 0) + +{{{ continue from paused state }}} + +As we can see, the lower upper limits of x-axis in the question are -1 and 3. +The limits of y-axis are -15 and 0. + +:: + + xlim(-1, 3) + ylim(-15, 0) + +Gives us the required rectangle. + +{{{ Show summary slide }}} + +we have looked at + + * Modifying the attributes of plot by passing additional arguments + * How to add title + * How to incorporate LaTex style formatting + * How to label x and y axes + * How to add annotations + * How to set the limits of axes + +{{{ Show the "sponsored by FOSSEE" slide }}} + +.. #[Nishanth]: Will add this line after all of us fix on one. + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thankyou + + diff -r 9bc78792904b -r 0ff3f1a97068 embellishing_a_plot/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/embellishing_a_plot/slides.tex Fri Oct 08 11:32:09 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 9bc78792904b -r 0ff3f1a97068 input_output.rst --- a/input_output.rst Fri Oct 08 11:31:56 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,288 +0,0 @@ -Hello friends and welcome to the tutorial on Input/Output - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -Input and Output are used in almost every program we use. -In this tutorial, we shall learn - - * Outputting data - * Taking input from the user - -type -:: - - a = "This is a string" - a - print a - -print a prints the value of a which is obvious. -As you can see, even when you type just a, the value of a is shown. -But there is a difference. - -Typing a shows the value of a while print a prints the string. This difference -becomes more evident when we use strings with newlines in them. -type -:: - - b = "A line \n New line" - b - print b - -As you can see, just typing b shows that b contains a newline character. -While typing print b prints the string and hence the newline. - -Moreover when we type just a, the value a is shown only in interactive mode and -does not have any effect on the program while running it as a script. - -We shall look at different ways of outputting the data. - -print statement also accepts the syntax of C's printf statement. -Various arguments can be passed to print using modifiers. -type -:: - - x = 1.5 - y = 2 - z = "zed" - print "x is %2.1f y is %d z is %s"%(x,y) - -As you can see, the values of x and y are substituted in place of %2.1f and %d - -{{{ Pause here and try out the following exercises }}} - -%% 1 %% What happens when you do print "x is %d y is %f"%(x) - -{{{ continue from paused state }}} - -We see that the int value of x and float value of y are printed corresponding -to the modifiers used in the print statement. - -We can also see that print statement prints a new line character at the end of -line, everytime it is called. This can be suppressed by using a "," at the end -print statement. - -Let us see this by typing out following code on an editor as print_example.py - -{{{ open an editor }}} -type -:: - - print "Hello" - print "World" - - print "Hello", - print "World" - -Now we run the script using %run /home/fossee/print_example.py - -As we can see, the print statement when used with comma in the end, prints a -space instead of a new line. - -Now we shall look at taking input from the user. -We will use the ~~raw_input~~ for this. -type -:: - - ip = raw_input() - -The cursor is blinking indicating that it is waiting for input -type -:: - - an input - -and hit enter. -Now let us see what is the value of ip by typing. -:: - - ip - -We can see that it contains the string "an input" - -{{{ Pause here and try out the following exercises }}} - -%% 2 %% enter the number 5.6 as input and store it in a variable called c. - -{{{ continue from paused state }}} - -We have to use the raw_input command with variable c. -type -:: - - c = raw_input() - 5.6 - c - -Now let us see the type of c. - -:: - - type(c) - -We see that c is a string. This implies that anything you enter as input, will -be taken as a string no matter what you enter. - -{{{ Pause here and try out the following exercises }}} - -%% 3 %% What happens when you do not enter anything and hit enter - -{{{ continue from paused state }}} - -:: - - d = raw_input() - - d - -We see that when nothing is entered, an empty string is considered as input. - -raw_input also can display a prompt to assist the user. -:: - - name = raw_input("Please enter your name: ") - -prints the string given as argument and then waits for the user input. - -{{{ Pause here and try out the following exercises }}} - -%% 4 %% How do you display a prompt and let the user enter input in a new line - -{{{ continue from paused state }}} - -The trick is to include a newline character at the end of the prompt string. -:: - - ip = raw_input("Please enter a number in the next line\n> ") - -prints the newline character and hence the user enters input in the new line - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial. -we have learnt - - * How to print some value - * How to print using modifiers - * How to take input from user - * How to display a prompt to the user before taking the input - -{{{ Show the "sponsored by FOSSEE" slide }}} - -#[Nishanth]: Will add this line after all of us fix on one. -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thankyou - -.. Author : Nishanth - Internal Reviewer 1 : - Internal Reviewer 2 : - External Reviewer : - -Questions -========= - - 1. ``a = 2.5``. What is the output of ``print "a is %d"%(a)`` - - a. a is 2.5 - #. a is 2.0 - #. 2.0 - #. a is 2 - - Answer: a is 2 - - 2. What does ``print "This is", "a line ", "with spaces"`` print? - - a. This is a line with spaces - #. This is a line with spaces - #. This is a line with spaces - #. This is a line with spaces - - Answer: This is a line with spaces - - 3. What does ``print "%2.5f"%(1.2)`` print? - - a. 1.2 - #. 1.20 - #. 1.20000 - #. 00001.2 - - Answer: 1.20000 - - 4. What is the output of the following code:: - - for i in range(1,10,2): - print i, - - Answer:: - - 1 3 5 7 9 - - 5. ``a = 2`` and ``b = 4.5``. What does ``print "a is %d and b is %2.1f"%(b, a)`` - print? - - a. a is 2 and b is 4.5 - #. a is 4 and b is 2 - #. a is 4 and b is 2.0 - #. a is 4.5 and b is 2 - - Answer: a is 4 and b is 2.0 - - 6. What is the prompt displayed by ``raw_input("Say something\nType here:")`` - - Answer:: - - Say something - Type here: - - 6. What is the prompt displayed by ``raw_input("value of a is %d\nInput b - value:"a)`` and ``a = 2.5`` - - Answer:: - - value of a is 2 - Input ba value: - - 7. ``a = raw_input()`` and user enters ``2.5``. What is the type of a? - - a. str - #. int - #. float - #. char - - Answer: str - - 8. ``a = int(raw_input())`` and user enters ``4.5``. What happens? - - a. a = 4.5 - #. a = 4 - #. a = 4.0 - #. Error - - Answer: Error - - 9. ``a = raw_input()`` and user enters ``"this is a string"``. What does - ``print a`` produce? - - a. 'this is a string' - b. 'this is a string" - c. "this is a string" - #. this is a string - - Answer: "this is a string" - -Problems -======== - - 1. Answer to universe and everything. Keep taking input from user and print it - back until the input is 42. - - Answer:: - - ip = raw_input() - while ip != "42": - print ip - - 2. diff -r 9bc78792904b -r 0ff3f1a97068 input_output/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/input_output/questions.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,105 @@ +Objective Questions +------------------- + + 1. ``a = 2.5``. What is the output of ``print "a is %d"%(a)`` + + a. a is 2.5 + #. a is 2.0 + #. 2.0 + #. a is 2 + + Answer: a is 2 + + 2. What does ``print "This is", "a line ", "with spaces"`` print? + + a. This is a line with spaces + #. This is a line with spaces + #. This is a line with spaces + #. This is a line with spaces + + Answer: This is a line with spaces + + 3. What does ``print "%2.5f"%(1.2)`` print? + + a. 1.2 + #. 1.20 + #. 1.20000 + #. 00001.2 + + Answer: 1.20000 + + 4. What is the output of the following code:: + + for i in range(1,10,2): + print i, + + Answer:: + + 1 3 5 7 9 + + 5. ``a = 2`` and ``b = 4.5``. What does ``print "a is %d and b is %2.1f"%(b, a)`` + print? + + a. a is 2 and b is 4.5 + #. a is 4 and b is 2 + #. a is 4 and b is 2.0 + #. a is 4.5 and b is 2 + + Answer: a is 4 and b is 2.0 + + 6. What is the prompt displayed by ``raw_input("Say something\nType here:")`` + + Answer:: + + Say something + Type here: + + 6. What is the prompt displayed by ``raw_input("value of a is %d\nInput b + value:"a)`` and ``a = 2.5`` + + Answer:: + + value of a is 2 + Input ba value: + + 7. ``a = raw_input()`` and user enters ``2.5``. What is the type of a? + + a. str + #. int + #. float + #. char + + Answer: str + + 8. ``a = int(raw_input())`` and user enters ``4.5``. What happens? + + a. a = 4.5 + #. a = 4 + #. a = 4.0 + #. Error + + Answer: Error + + 9. ``a = raw_input()`` and user enters ``"this is a string"``. What does + ``print a`` produce? + + a. 'this is a string' + b. 'this is a string" + c. "this is a string" + #. this is a string + + Answer: "this is a string" + +Larger Questions +================ + + 1. Answer to universe and everything. Keep taking input from user and print it + back until the input is 42. + + Answer:: + + ip = raw_input() + while ip != "42": + print ip + + diff -r 9bc78792904b -r 0ff3f1a97068 input_output/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/input_output/quickref.tex Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,11 @@ +Creating a tuple:\\ +{\ex \lstinline| t = (1, "hello", 2.5)|} + +Accessing elements of tuples:\\ +{\ex \lstinline| t[index] Ex: t[2]|} + +Accessing slices of tuples:\\ +{\ex \lstinline| t[start:stop:step]|} + +Swapping values:\\ +{\ex \lstinline| a, b = b, a|} diff -r 9bc78792904b -r 0ff3f1a97068 input_output/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/input_output/script.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,199 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - + C - + D - + +.. Prerequisites +.. ------------- + +.. 1. Loops + +.. Author : Nishanth Amuluru + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +Hello friends and welcome to the tutorial on Input/Output + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +Input and Output are used in almost every program we use. +In this tutorial, we shall learn + + * Outputting data + * Taking input from the user + +type +:: + + a = "This is a string" + a + print a + +print a prints the value of a which is obvious. +As you can see, even when you type just a, the value of a is shown. +But there is a difference. + +Typing a shows the value of a while print a prints the string. This difference +becomes more evident when we use strings with newlines in them. +type +:: + + b = "A line \n New line" + b + print b + +As you can see, just typing b shows that b contains a newline character. +While typing print b prints the string and hence the newline. + +Moreover when we type just a, the value a is shown only in interactive mode and +does not have any effect on the program while running it as a script. + +We shall look at different ways of outputting the data. + +print statement also accepts the syntax of C's printf statement. +Various arguments can be passed to print using modifiers. +type +:: + + x = 1.5 + y = 2 + z = "zed" + print "x is %2.1f y is %d z is %s"%(x,y) + +As you can see, the values of x and y are substituted in place of %2.1f and %d + +{{{ Pause here and try out the following exercises }}} + +%% 1 %% What happens when you do print "x is %d y is %f"%(x) + +{{{ continue from paused state }}} + +We see that the int value of x and float value of y are printed corresponding +to the modifiers used in the print statement. + +We can also see that print statement prints a new line character at the end of +line, everytime it is called. This can be suppressed by using a "," at the end +print statement. + +Let us see this by typing out following code on an editor as print_example.py + +{{{ open an editor }}} +type +:: + + print "Hello" + print "World" + + print "Hello", + print "World" + +Now we run the script using %run /home/fossee/print_example.py + +As we can see, the print statement when used with comma in the end, prints a +space instead of a new line. + +Now we shall look at taking input from the user. +We will use the ~~raw_input~~ for this. +type +:: + + ip = raw_input() + +The cursor is blinking indicating that it is waiting for input +type +:: + + an input + +and hit enter. +Now let us see what is the value of ip by typing. +:: + + ip + +We can see that it contains the string "an input" + +{{{ Pause here and try out the following exercises }}} + +%% 2 %% enter the number 5.6 as input and store it in a variable called c. + +{{{ continue from paused state }}} + +We have to use the raw_input command with variable c. +type +:: + + c = raw_input() + 5.6 + c + +Now let us see the type of c. + +:: + + type(c) + +We see that c is a string. This implies that anything you enter as input, will +be taken as a string no matter what you enter. + +{{{ Pause here and try out the following exercises }}} + +%% 3 %% What happens when you do not enter anything and hit enter + +{{{ continue from paused state }}} + +:: + + d = raw_input() + + d + +We see that when nothing is entered, an empty string is considered as input. + +raw_input also can display a prompt to assist the user. +:: + + name = raw_input("Please enter your name: ") + +prints the string given as argument and then waits for the user input. + +{{{ Pause here and try out the following exercises }}} + +%% 4 %% How do you display a prompt and let the user enter input in a new line + +{{{ continue from paused state }}} + +The trick is to include a newline character at the end of the prompt string. +:: + + ip = raw_input("Please enter a number in the next line\n> ") + +prints the newline character and hence the user enters input in the new line + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have learnt + + * How to print some value + * How to print using modifiers + * How to take input from user + * How to display a prompt to the user before taking the input + +{{{ Show the "sponsored by FOSSEE" slide }}} + +#[Nishanth]: Will add this line after all of us fix on one. +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thankyou + diff -r 9bc78792904b -r 0ff3f1a97068 input_output/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/input_output/slides.tex Fri Oct 08 11:32:09 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 9bc78792904b -r 0ff3f1a97068 lstsq.rst --- a/lstsq.rst Fri Oct 08 11:31:56 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,139 +0,0 @@ -.. Author : Nishanth - Internal Reviewer 1 : Puneeth - Internal Reviewer 2 : - External Reviewer : - -Hello friends and welcome to the tutorial on Least Square Fit - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall look at generating the least square fit line for a -given set of points. - -First let us have a look at the problem. - -{{{ Show the slide containing problem statement. }}} - -We have an input file generated from a simple pendulum experiment. - -It contains two columns of data. The first column is the length of the -pendulum and the second is the corresponding time period of the pendulum. - -As we know, the square of time period of a pendulum is directly proportional to -its length, we shall plot l vs t^2 and verify this. - -#[Puneeth:] removed the explanation about loadtxt and unpack - option. It's been done in another LO already. simple dependency - should work? - -To read the input file and parse the data, we are going to use the -loadtxt function. Type -:: - - l, t = loadtxt("/home/fossee/pendulum.txt", unpack=True) - l - t - -We can see that l and t are two sequences containing length and time values -correspondingly. - -Let us first plot l vs t^2. Type -:: - - tsq = t * t - plot(l, tsq, 'bo') - -{{{ switch to the plot window }}} - -#[Puneeth:] Moved explanation of least square fit here. seems more -apt. - -We can see that there is a visible linear trend, but we do not get a -straight line connecting them. We shall, therefore, generate a least -square fit line. - -{{{ show the slide containing explanation on least square fit }}} - -As shown in the slide, we are first going to generate the two matrices -tsq and A. Then we are going to use the ``lstsq`` function to find the -values of m and c. - -let us now generate the A matrix with l values. -We shall first generate a 2 x 90 matrix with the first row as l values and the -second row as ones. Then take the transpose of it. Type -:: - - inter_mat = array((l, ones_like(l))) - inter_mat - -We see that we have intermediate matrix. Now we need the transpose. Type -:: - - A = inter_mat.T - A - -Now we have both the matrices A and tsq. We only need to use the ``lstsq`` -Type -:: - - result = lstsq(A, tsq) - -The result is a sequence of values. The first item in this sequence, -is the matrix p i.e., the values of m and c. Hence, -:: - - m, c = result[0] - m - c - -Now that we have m and c, we need to generate the fitted values of t^2. Type -:: - - tsq_fit = m * l + c - plot(l, tsq, 'bo') - plot(l, tsq_fit, 'r') - -We get the least square fit of l vs t^2 - -{{{ Pause here and try out the following exercises }}} - -%% 2 %% change the label on y-axis to "y" and save the lines of code - accordingly - -{{{ continue from paused state }}} - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial. -we have learnt - - * how to generate a least square fit - -{{{ Show the "sponsored by FOSSEE" slide }}} - -#[Nishanth]: Will add this line after all of us fix on one. -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thank you - -Questions -========= - - 1. What does ones_like([1, 2, 3]) produce - - a. array([1, 1, 1]) - #. [1, 1, 1] - #. [1.0, 1.0, 1.0] - #. Error - - 2. What does ones_like([1.2, 3, 4, 5]) produce - - a. [1.2, 3, 4, 5] - #. array([1.0, 1.0, 1.0, 1.0]) - #. array([1, 1, 1, 1]) - #. array([1.2, 3, 4, 5]) - - 3. What is the shape of the diff -r 9bc78792904b -r 0ff3f1a97068 lstsq/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lstsq/questions.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,18 @@ +Objective Questions +------------------- + + 1. What does ones_like([1, 2, 3]) produce + + a. array([1, 1, 1]) + #. [1, 1, 1] + #. [1.0, 1.0, 1.0] + #. Error + + 2. What does ones_like([1.2, 3, 4, 5]) produce + + a. [1.2, 3, 4, 5] + #. array([1.0, 1.0, 1.0, 1.0]) + #. array([1, 1, 1, 1]) + #. array([1.2, 3, 4, 5]) + + diff -r 9bc78792904b -r 0ff3f1a97068 lstsq/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lstsq/quickref.tex Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,11 @@ +Creating a tuple:\\ +{\ex \lstinline| t = (1, "hello", 2.5)|} + +Accessing elements of tuples:\\ +{\ex \lstinline| t[index] Ex: t[2]|} + +Accessing slices of tuples:\\ +{\ex \lstinline| t[start:stop:step]|} + +Swapping values:\\ +{\ex \lstinline| a, b = b, a|} diff -r 9bc78792904b -r 0ff3f1a97068 lstsq/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lstsq/script.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,139 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - + C - + D - + +.. Prerequisites +.. ------------- + +.. 1. Basic Plotting + 2. Arrays + +.. Author : Nishanth Amuluru + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +Hello friends and welcome to the tutorial on Least Square Fit + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall look at generating the least square fit line for a +given set of points. + +First let us have a look at the problem. + +{{{ Show the slide containing problem statement. }}} + +We have an input file generated from a simple pendulum experiment. + +It contains two columns of data. The first column is the length of the +pendulum and the second is the corresponding time period of the pendulum. + +As we know, the square of time period of a pendulum is directly proportional to +its length, we shall plot l vs t^2 and verify this. + +#[Puneeth:] removed the explanation about loadtxt and unpack + option. It's been done in another LO already. simple dependency + should work? + +To read the input file and parse the data, we are going to use the +loadtxt function. Type +:: + + l, t = loadtxt("/home/fossee/pendulum.txt", unpack=True) + l + t + +We can see that l and t are two sequences containing length and time values +correspondingly. + +Let us first plot l vs t^2. Type +:: + + tsq = t * t + plot(l, tsq, 'bo') + +{{{ switch to the plot window }}} + +#[Puneeth:] Moved explanation of least square fit here. seems more +apt. + +We can see that there is a visible linear trend, but we do not get a +straight line connecting them. We shall, therefore, generate a least +square fit line. + +{{{ show the slide containing explanation on least square fit }}} + +As shown in the slide, we are first going to generate the two matrices +tsq and A. Then we are going to use the ``lstsq`` function to find the +values of m and c. + +let us now generate the A matrix with l values. +We shall first generate a 2 x 90 matrix with the first row as l values and the +second row as ones. Then take the transpose of it. Type +:: + + inter_mat = array((l, ones_like(l))) + inter_mat + +We see that we have intermediate matrix. Now we need the transpose. Type +:: + + A = inter_mat.T + A + +Now we have both the matrices A and tsq. We only need to use the ``lstsq`` +Type +:: + + result = lstsq(A, tsq) + +The result is a sequence of values. The first item in this sequence, +is the matrix p i.e., the values of m and c. Hence, +:: + + m, c = result[0] + m + c + +Now that we have m and c, we need to generate the fitted values of t^2. Type +:: + + tsq_fit = m * l + c + plot(l, tsq, 'bo') + plot(l, tsq_fit, 'r') + +We get the least square fit of l vs t^2 + +{{{ Pause here and try out the following exercises }}} + +%% 2 %% change the label on y-axis to "y" and save the lines of code + accordingly + +{{{ continue from paused state }}} + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have learnt + + * how to generate a least square fit + +{{{ Show the "sponsored by FOSSEE" slide }}} + +#[Nishanth]: Will add this line after all of us fix on one. +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you + + diff -r 9bc78792904b -r 0ff3f1a97068 lstsq/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lstsq/slides.tex Fri Oct 08 11:32:09 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 9bc78792904b -r 0ff3f1a97068 parsing_data.rst --- a/parsing_data.rst Fri Oct 08 11:31:56 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,287 +0,0 @@ -.. Author : Nishanth - Internal Reviewer 1 : - Internal Reviewer 2 : - External Reviewer : - -Hello friends and welcome to the tutorial on Parsing Data - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall learn - - * What we mean by parsing data - * the string operations required for parsing data - * datatype conversion - -#[Puneeth]: Changed a few things, here. - -#[Puneeth]: I don't like the way the term "parsing data" has been used, all -through the script. See if that can be changed. - - Lets us have a look at the problem - -{{{ Show the slide containing problem statement. }}} - -There is an input file containing huge no. of records. Each record corresponds -to a student. - -{{{ show the slide explaining record structure }}} -As you can see, each record consists of fields seperated by a ";". The first -record is region code, then roll number, then name, marks of second language, -first language, maths, science and social, total marks, pass/fail indicatd by P -or F and finally W if with held and empty otherwise. - -Our job is to calculate the mean of all the maths marks in the region "B". - -#[Nishanth]: Please note that I am not telling anything about AA since they do - not know about any if/else yet. - -#[Puneeth]: Should we talk pass/fail etc? I think we should make the problem - simple and leave out all the columns after total marks. - -Now what is parsing data. - -From the input file, we can see that the data we have is in the form of -text. Parsing this data is all about reading it and converting it into a form -which can be used for computations -- in our case, sequence of numbers. - -#[Puneeth]: should the word tokenizing, be used? Should it be defined before - using it? - -We can clearly see that the problem involves reading files and tokenizing. - -#[Puneeth]: the sentence above seems kinda redundant. - -Let us learn about tokenizing strings. Let us define a string first. Type -:: - - line = "parse this string" - -We are now going to split this string on whitespace. -:: - - line.split() - -As you can see, we get a list of strings. Which means, when ``split`` is called -without any arguments, it splits on whitespace. In simple words, all the spaces -are treated as one big space. - -``split`` also can split on a string of our choice. This is acheived by passing -that as an argument. But first lets define a sample record from the file. -:: - - record = "A;015163;JOSEPH RAJ S;083;042;47;AA;72;244;;;" - record.split(';') - -We can see that the string is split on ';' and we get each field seperately. -We can also observe that an empty string appears in the list since there are -two semi colons without anything in between. - -To recap, ``split`` splits on whitespace if called without an argument and -splits on the given argument if it is called with an argument. - -{{{ Pause here and try out the following exercises }}} - -%% 1 %% split the variable line using a space as argument. Is it same as - splitting without an argument ? - -{{{ continue from paused state }}} - -We see that when we split on space, multiple whitespaces are not clubbed as one -and there is an empty string everytime there are two consecutive spaces. - -Now that we know how to split a string, we can split the record and retrieve -each field seperately. But there is one problem. The region code "B" and a "B" -surrounded by whitespace are treated as two different regions. We must find a -way to remove all the whitespace around a string so that "B" and a "B" with -white spaces are dealt as same. - -This is possible by using the ``strip`` method of strings. Let us define a -string by typing -:: - - unstripped = " B " - unstripped.strip() - -We can see that strip removes all the whitespace around the sentence - -{{{ Pause here and try out the following exercises }}} - -%% 2 %% What happens to the white space inside the sentence when it is stripped - -{{{ continue from paused state }}} - -Type -:: - - a_str = " white space " - a_str.strip() - -We see that the whitespace inside the sentence is only removed and anything -inside remains unaffected. - -By now we know enough to seperate fields from the record and to strip out any -white space. The only road block we now have is conversion of string to float. - -The splitting and stripping operations are done on a string and their result is -also a string. hence the marks that we have are still strings and mathematical -operations are not possible on them. We must convert them into numbers -(integers or floats), before we can perform mathematical operations on them. - -We shall look at converting strings into floats. We define a float string -first. Type -:: - - mark_str = "1.25" - mark = int(mark_str) - type(mark_str) - type(mark) - -We can see that string is converted to float. We can perform mathematical -operations on them now. - -{{{ Pause here and try out the following exercises }}} - -%% 3 %% What happens if you do int("1.25") - -{{{ continue from paused state }}} - -It raises an error since converting a float string into integer directly is -not possible. It involves an intermediate step of converting to float. -:: - - dcml_str = "1.25" - flt = float(dcml_str) - flt - number = int(flt) - number - -Using ``int`` it is also possible to convert float into integers. - -Now that we have all the machinery required to parse the file, let us solve the -problem. We first read the file line by line and parse each record. We see if -the region code is B and store the marks accordingly. -:: - - math_marks_B = [] # an empty list to store the marks - for line in open("/home/fossee/sslc1.txt"): - fields = line.split(";") - - region_code = fields[0] - region_code_stripped = region_code.strip() - - math_mark_str = fields[5] - math_mark = float(math_mark_str) - - if region_code == "AA": - math_marks_B.append(math_mark) - - -Now we have all the maths marks of region "B" in the list math_marks_B. -To get the mean, we just have to sum the marks and divide by the length. -:: - - math_marks_mean = sum(math_marks_B) / len(math_marks_B) - math_marks_mean - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial. -we have learnt - - * how to tokenize a string using various delimiters - * how to get rid of extra white space around - * how to convert from one type to another - * how to parse input data and perform computations on it - -{{{ Show the "sponsored by FOSSEE" slide }}} - -#[Nishanth]: Will add this line after all of us fix on one. -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thank you - -Questions -========= - - 1. How do you split the string "Guido;Rossum;Python" to get the words - - Answer: line.split(';') - - 2. line.split() and line.split(' ') are same - - a. True - #. False - - Answer: False - - 3. What is the output of the following code:: - - line = "Hello;;;World;;" - sub_strs = line.split() - print len(sub_strs) - - Answer: 5 - - 4. What is the output of " Hello World ".strip() - - a. "Hello World" - #. "Hello World" - #. " Hello World" - #. "Hello World " - - Answer: "Hello World" - - 5. What does "It is a cold night".strip("It") produce - Hint: Read the documentation of strip - - a. "is a cold night" - #. " is a cold nigh" - #. "It is a cold nigh" - #. "is a cold nigh" - - Answer: " is a cold nigh" - - 6. What does int("20") produce - - a. "20" - #. 20.0 - #. 20 - #. Error - - Answer: 20 - - 7. What does int("20.0") produce - - a. 20 - #. 20.0 - #. Error - #. "20" - - Answer: Error - - 8. What is the value of float(3/2) - - a. 1.0 - #. 1.5 - #. 1 - #. Error - - Answer: 1.0 - - 9. what doess float("3/2") produce - - a. 1.0 - #. 1.5 - #. 1 - #. Error - - Answer: Error - - 10. See if there is a function available in pylab to calculate the mean - Hint: Use tab completion - - diff -r 9bc78792904b -r 0ff3f1a97068 parsing_data/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parsing_data/questions.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,102 @@ +Objective Questions +------------------- + + 1. How do you split the string "Guido;Rossum;Python" to get the words + + Answer: line.split(';') + + 2. line.split() and line.split(' ') are same + + a. True + #. False + + Answer: False + + 3. What is the output of the following code:: + + line = "Hello;;;World;;" + sub_strs = line.split() + print len(sub_strs) + + Answer: 5 + + 4. What is the output of " Hello World ".strip() + + a. "Hello World" + #. "Hello World" + #. " Hello World" + #. "Hello World " + + Answer: "Hello World" + + 5. What does "It is a cold night".strip("It") produce + Hint: Read the documentation of strip + + a. "is a cold night" + #. " is a cold nigh" + #. "It is a cold nigh" + #. "is a cold nigh" + + Answer: " is a cold nigh" + + 6. What does int("20") produce + + a. "20" + #. 20.0 + #. 20 + #. Error + + Answer: 20 + + 7. What does int("20.0") produce + + a. 20 + #. 20.0 + #. Error + #. "20" + + Answer: Error + + 8. What is the value of float(3/2) + + a. 1.0 + #. 1.5 + #. 1 + #. Error + + Answer: 1.0 + + 9. what doess float("3/2") produce + + a. 1.0 + #. 1.5 + #. 1 + #. Error + + Answer: Error + + 10. See if there is a function available in pylab to calculate the mean + Hint: Use tab completion + +Larger Questions +================ + + 1. The file ``pos.txt`` contains two columns of data. The first and second + columns are the x and y co-ordiantes of a particle in motion, respectively. + Plot the trajectory of the particle. + + Answer:: + + x_values = [] + y_values = [] + + for line in open("/home/fossee/pos.txt"); + x_str, y_str = line.split() + x = int(x_str) + y = int(y_str) + + x_values.append(x) + y_values.append(y) + + plot(x, y, 'b.') + diff -r 9bc78792904b -r 0ff3f1a97068 parsing_data/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parsing_data/quickref.tex Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,11 @@ +Creating a tuple:\\ +{\ex \lstinline| t = (1, "hello", 2.5)|} + +Accessing elements of tuples:\\ +{\ex \lstinline| t[index] Ex: t[2]|} + +Accessing slices of tuples:\\ +{\ex \lstinline| t[start:stop:step]|} + +Swapping values:\\ +{\ex \lstinline| a, b = b, a|} diff -r 9bc78792904b -r 0ff3f1a97068 parsing_data/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parsing_data/script.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,223 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - + C - + D - + +.. Prerequisites +.. ------------- + +.. 1. Getting started with lists + +.. Author : Nishanth Amuluru + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +Hello friends and welcome to the tutorial on Parsing Data + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall learn + + * What we mean by parsing data + * the string operations required for parsing data + * datatype conversion + +#[Puneeth]: Changed a few things, here. + +#[Puneeth]: I don't like the way the term "parsing data" has been used, all +through the script. See if that can be changed. + + Lets us have a look at the problem + +{{{ Show the slide containing problem statement. }}} + +There is an input file containing huge no. of records. Each record corresponds +to a student. + +{{{ show the slide explaining record structure }}} +As you can see, each record consists of fields seperated by a ";". The first +record is region code, then roll number, then name, marks of second language, +first language, maths, science and social, total marks, pass/fail indicatd by P +or F and finally W if with held and empty otherwise. + +Our job is to calculate the mean of all the maths marks in the region "B". + +#[Nishanth]: Please note that I am not telling anything about AA since they do + not know about any if/else yet. + +#[Puneeth]: Should we talk pass/fail etc? I think we should make the problem + simple and leave out all the columns after total marks. + +Now what is parsing data. + +From the input file, we can see that the data we have is in the form of +text. Parsing this data is all about reading it and converting it into a form +which can be used for computations -- in our case, sequence of numbers. + +#[Puneeth]: should the word tokenizing, be used? Should it be defined before + using it? + +We can clearly see that the problem involves reading files and tokenizing. + +#[Puneeth]: the sentence above seems kinda redundant. + +Let us learn about tokenizing strings. Let us define a string first. Type +:: + + line = "parse this string" + +We are now going to split this string on whitespace. +:: + + line.split() + +As you can see, we get a list of strings. Which means, when ``split`` is called +without any arguments, it splits on whitespace. In simple words, all the spaces +are treated as one big space. + +``split`` also can split on a string of our choice. This is acheived by passing +that as an argument. But first lets define a sample record from the file. +:: + + record = "A;015163;JOSEPH RAJ S;083;042;47;AA;72;244;;;" + record.split(';') + +We can see that the string is split on ';' and we get each field seperately. +We can also observe that an empty string appears in the list since there are +two semi colons without anything in between. + +To recap, ``split`` splits on whitespace if called without an argument and +splits on the given argument if it is called with an argument. + +{{{ Pause here and try out the following exercises }}} + +%% 1 %% split the variable line using a space as argument. Is it same as + splitting without an argument ? + +{{{ continue from paused state }}} + +We see that when we split on space, multiple whitespaces are not clubbed as one +and there is an empty string everytime there are two consecutive spaces. + +Now that we know how to split a string, we can split the record and retrieve +each field seperately. But there is one problem. The region code "B" and a "B" +surrounded by whitespace are treated as two different regions. We must find a +way to remove all the whitespace around a string so that "B" and a "B" with +white spaces are dealt as same. + +This is possible by using the ``strip`` method of strings. Let us define a +string by typing +:: + + unstripped = " B " + unstripped.strip() + +We can see that strip removes all the whitespace around the sentence + +{{{ Pause here and try out the following exercises }}} + +%% 2 %% What happens to the white space inside the sentence when it is stripped + +{{{ continue from paused state }}} + +Type +:: + + a_str = " white space " + a_str.strip() + +We see that the whitespace inside the sentence is only removed and anything +inside remains unaffected. + +By now we know enough to seperate fields from the record and to strip out any +white space. The only road block we now have is conversion of string to float. + +The splitting and stripping operations are done on a string and their result is +also a string. hence the marks that we have are still strings and mathematical +operations are not possible on them. We must convert them into numbers +(integers or floats), before we can perform mathematical operations on them. + +We shall look at converting strings into floats. We define a float string +first. Type +:: + + mark_str = "1.25" + mark = int(mark_str) + type(mark_str) + type(mark) + +We can see that string is converted to float. We can perform mathematical +operations on them now. + +{{{ Pause here and try out the following exercises }}} + +%% 3 %% What happens if you do int("1.25") + +{{{ continue from paused state }}} + +It raises an error since converting a float string into integer directly is +not possible. It involves an intermediate step of converting to float. +:: + + dcml_str = "1.25" + flt = float(dcml_str) + flt + number = int(flt) + number + +Using ``int`` it is also possible to convert float into integers. + +Now that we have all the machinery required to parse the file, let us solve the +problem. We first read the file line by line and parse each record. We see if +the region code is B and store the marks accordingly. +:: + + math_marks_B = [] # an empty list to store the marks + for line in open("/home/fossee/sslc1.txt"): + fields = line.split(";") + + region_code = fields[0] + region_code_stripped = region_code.strip() + + math_mark_str = fields[5] + math_mark = float(math_mark_str) + + if region_code == "AA": + math_marks_B.append(math_mark) + + +Now we have all the maths marks of region "B" in the list math_marks_B. +To get the mean, we just have to sum the marks and divide by the length. +:: + + math_marks_mean = sum(math_marks_B) / len(math_marks_B) + math_marks_mean + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have learnt + + * how to tokenize a string using various delimiters + * how to get rid of extra white space around + * how to convert from one type to another + * how to parse input data and perform computations on it + +{{{ Show the "sponsored by FOSSEE" slide }}} + +#[Nishanth]: Will add this line after all of us fix on one. +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you + + diff -r 9bc78792904b -r 0ff3f1a97068 parsing_data/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parsing_data/slides.tex Fri Oct 08 11:32:09 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 9bc78792904b -r 0ff3f1a97068 sets.rst --- a/sets.rst Fri Oct 08 11:31:56 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,240 +0,0 @@ -Hello friends and welcome to the tutorial on Sets - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall learn - - * sets - * operations on sets - -Sets are data structures which contain unique elements. In other words, -duplicates are not allowed in sets. - -Lets look at how to input sets. -type -:: - - a_list = [1, 2, 1, 4, 5, 6, 7] - a = set(a_list) - a - -We can see that duplicates are removed and the set contains only unique -elements. -:: - - f10 = set([1, 2, 3, 5, 8]) - p10 = set([2, 3, 5, 7]) - -f10 is the set of fibonacci numbers from 1 to 10. -p10 is the set of prime numbers from 1 to 10. - -Various operations that we do on sets are possible here also. -The | character stands for union -:: - - f10 | p10 - -gives us the union of f10 and p10 - -The & character stands for intersection. -:: - - f10 & p10 - -gives the intersection - -similarly, -:: - - f10 - p10 - -gives all the elements that are in f10 but not in p10 - -:: - - f10 ^ p10 - -is all the elements in f10 union p10 but not in f10 intersection p10. In -mathematical terms, it gives the symmectric difference. - -Sets also support checking of subsets. -:: - - b = set([1, 2]) - b < f10 - -gives a True since b is a proper subset of f10. -Similarly, -:: - - f10 < f10 - -gives a False since f10 is not a proper subset. -hence the right way to do would be -:: - - f10 <= f10 - -and we get a True since every set is a subset of itself. - -Sets can be iterated upon just like lists and tuples. -:: - - for i in f10: - print i, - -prints the elements of f10. - -The length and containership check on sets is similar as in lists and tuples. -:: - - len(f10) - -shows 5. And -:: - - 1 in f10 - 2 in f10 - -prints True and False respectively - -The order in which elements are organised in a set is not to be relied upon -since sets do not support indexing. Hence, slicing and striding are not valid -on sets. - -{{{ Pause here and try out the following exercises }}} - -%% 1 %% Given a list of marks, marks = [20, 23, 22, 23, 20, 21, 23] - list all the duplicates - -{{{ continue from paused state }}} - -Duplicates marks are the marks left out when we remove each element of the -list exactly one time. - -:: - - marks = [20, 23, 22, 23, 20, 21, 23] - marks_set = set(marks) - for mark in marks_set: - marks.remove(mark) - - # we are now left with only duplicates in the list marks - duplicates = set(marks) - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial. -we have learnt - - * How to make sets from lists - * How to input sets - * How to perform union, intersection and symmectric difference operations - * How to check if a set is a subset of other - * The various similarities with lists like length and containership - -{{{ Show the "sponsored by FOSSEE" slide }}} - -#[Nishanth]: Will add this line after all of us fix on one. -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thankyou - -.. Author : Nishanth - Internal Reviewer 1 : - Internal Reviewer 2 : - External Reviewer : - - -Questions -========= - - 1. If ``a = [1, 1, 2, 3, 3, 5, 5, 8]``. What is set(a) - - a. set([1, 1, 2, 3, 3, 5, 5, 8]) - #. set([1, 2, 3, 5, 8]) - #. set([1, 2, 3, 3, 5, 5]) - #. Error - - Answer: set([1, 2, 3, 5, 8]) - - 2. ``a = set([1, 3, 5])``. How do you find the length of a? - - Answer: len(a) - - 3. ``a = set([1, 3, 5])``. What does a[2] produce? - - a. 1 - #. 3 - #. 5 - #. Error - - Answer: Error - - 4. ``odd = set([1, 3, 5, 7, 9])`` and ``squares = set([1, 4, 9, 16])``. What - is the value of ``odd | squares``? - - Answer: set([1, 3, 4, 5, 7, 9, 16]) - - 5. ``odd = set([1, 3, 5, 7, 9])`` and ``squares = set([1, 4, 9, 16])``. What - is the value of ``odd - squares``? - - Answer: set([3, 5, 7]) - - 6. ``odd = set([1, 3, 5, 7, 9])`` and ``squares = set([1, 4, 9, 16])``. What - is the value of ``odd ^ squares``? - - Answer: set([3, 4, 5, 7, 16]) - - 7. ``odd = set([1, 3, 5, 7, 9])`` and ``squares = set([1, 4, 9, 16])``. What - does ``odd * squares`` give? - - a. set([1, 12, 45, 112, 9]) - #. set([1, 3, 4, 5, 7, 9, 16]) - #. set([]) - #. Error - - Answer: Error - - 8. ``a = set([1, 2, 3, 4])`` and ``b = set([5, 6, 7, 8])``. What is ``a + b`` - - a. set([1, 2, 3, 4, 5, 6, 7, 8]) - #. set([6, 8, 10, 12]) - #. set([5, 12, 21, 32]) - #. Error - - 9. ``a`` is a set. how do you check if if a varaible ``b`` exists in ``a``? - - Answer: b in a - - 10. ``a`` and ``b`` are two sets. What is ``a ^ b == (a - b) | (b - a)``? - - a. True - #. False - - Answer: False - - -Problems -======== - - 1. Given that mat_marks is a list of maths marks of a class. Find out the - no.of duplicates marks in the list. - - Answer:: - - unique_marks = set(mat_marks) - no_of_duplicates = len(mat_marks) - len(unique_marks) - - 2. Given that mat_marks is a list of maths marks of a class. Find how many - duplicates of each mark exist. - - Answer:: - - marks_set = set(mat_marks) - for mark in marks_set: - occurences = mat_marks.count(mark) - print occurences - 1, "duplicates of", mark, "exist" diff -r 9bc78792904b -r 0ff3f1a97068 sets/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sets/questions.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,90 @@ +Objective Questions +------------------- + + 1. If ``a = [1, 1, 2, 3, 3, 5, 5, 8]``. What is set(a) + + a. set([1, 1, 2, 3, 3, 5, 5, 8]) + #. set([1, 2, 3, 5, 8]) + #. set([1, 2, 3, 3, 5, 5]) + #. Error + + Answer: set([1, 2, 3, 5, 8]) + + 2. ``a = set([1, 3, 5])``. How do you find the length of a? + + Answer: len(a) + + 3. ``a = set([1, 3, 5])``. What does a[2] produce? + + a. 1 + #. 3 + #. 5 + #. Error + + Answer: Error + + 4. ``odd = set([1, 3, 5, 7, 9])`` and ``squares = set([1, 4, 9, 16])``. What + is the value of ``odd | squares``? + + Answer: set([1, 3, 4, 5, 7, 9, 16]) + + 5. ``odd = set([1, 3, 5, 7, 9])`` and ``squares = set([1, 4, 9, 16])``. What + is the value of ``odd - squares``? + + Answer: set([3, 5, 7]) + + 6. ``odd = set([1, 3, 5, 7, 9])`` and ``squares = set([1, 4, 9, 16])``. What + is the value of ``odd ^ squares``? + + Answer: set([3, 4, 5, 7, 16]) + + 7. ``odd = set([1, 3, 5, 7, 9])`` and ``squares = set([1, 4, 9, 16])``. What + does ``odd * squares`` give? + + a. set([1, 12, 45, 112, 9]) + #. set([1, 3, 4, 5, 7, 9, 16]) + #. set([]) + #. Error + + Answer: Error + + 8. ``a = set([1, 2, 3, 4])`` and ``b = set([5, 6, 7, 8])``. What is ``a + b`` + + a. set([1, 2, 3, 4, 5, 6, 7, 8]) + #. set([6, 8, 10, 12]) + #. set([5, 12, 21, 32]) + #. Error + + 9. ``a`` is a set. how do you check if if a varaible ``b`` exists in ``a``? + + Answer: b in a + + 10. ``a`` and ``b`` are two sets. What is ``a ^ b == (a - b) | (b - a)``? + + a. True + #. False + + Answer: False + + +Larger Questions +---------------- + + 1. Given that mat_marks is a list of maths marks of a class. Find out the + no.of duplicates marks in the list. + + Answer:: + + unique_marks = set(mat_marks) + no_of_duplicates = len(mat_marks) - len(unique_marks) + + 2. Given that mat_marks is a list of maths marks of a class. Find how many + duplicates of each mark exist. + + Answer:: + + marks_set = set(mat_marks) + for mark in marks_set: + occurences = mat_marks.count(mark) + print occurences - 1, "duplicates of", mark, "exist" + diff -r 9bc78792904b -r 0ff3f1a97068 sets/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sets/quickref.tex Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,11 @@ +Creating a tuple:\\ +{\ex \lstinline| t = (1, "hello", 2.5)|} + +Accessing elements of tuples:\\ +{\ex \lstinline| t[index] Ex: t[2]|} + +Accessing slices of tuples:\\ +{\ex \lstinline| t[start:stop:step]|} + +Swapping values:\\ +{\ex \lstinline| a, b = b, a|} diff -r 9bc78792904b -r 0ff3f1a97068 sets/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sets/script.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,167 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - Will learn what are tuples and why they are needed + Will learn the various methods of accessing elements in tuples + C - + D - + +.. Prerequisites +.. ------------- + +.. 1. Getting started with lists + +.. Author : Nishanth Amuluru + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +Hello friends and welcome to the tutorial on Sets + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall learn + + * sets + * operations on sets + +Sets are data structures which contain unique elements. In other words, +duplicates are not allowed in sets. + +Lets look at how to input sets. +type +:: + + a_list = [1, 2, 1, 4, 5, 6, 7] + a = set(a_list) + a + +We can see that duplicates are removed and the set contains only unique +elements. +:: + + f10 = set([1, 2, 3, 5, 8]) + p10 = set([2, 3, 5, 7]) + +f10 is the set of fibonacci numbers from 1 to 10. +p10 is the set of prime numbers from 1 to 10. + +Various operations that we do on sets are possible here also. +The | character stands for union +:: + + f10 | p10 + +gives us the union of f10 and p10 + +The & character stands for intersection. +:: + + f10 & p10 + +gives the intersection + +similarly, +:: + + f10 - p10 + +gives all the elements that are in f10 but not in p10 + +:: + + f10 ^ p10 + +is all the elements in f10 union p10 but not in f10 intersection p10. In +mathematical terms, it gives the symmectric difference. + +Sets also support checking of subsets. +:: + + b = set([1, 2]) + b < f10 + +gives a True since b is a proper subset of f10. +Similarly, +:: + + f10 < f10 + +gives a False since f10 is not a proper subset. +hence the right way to do would be +:: + + f10 <= f10 + +and we get a True since every set is a subset of itself. + +Sets can be iterated upon just like lists and tuples. +:: + + for i in f10: + print i, + +prints the elements of f10. + +The length and containership check on sets is similar as in lists and tuples. +:: + + len(f10) + +shows 5. And +:: + + 1 in f10 + 2 in f10 + +prints True and False respectively + +The order in which elements are organised in a set is not to be relied upon +since sets do not support indexing. Hence, slicing and striding are not valid +on sets. + +{{{ Pause here and try out the following exercises }}} + +%% 1 %% Given a list of marks, marks = [20, 23, 22, 23, 20, 21, 23] + list all the duplicates + +{{{ continue from paused state }}} + +Duplicates marks are the marks left out when we remove each element of the +list exactly one time. + +:: + + marks = [20, 23, 22, 23, 20, 21, 23] + marks_set = set(marks) + for mark in marks_set: + marks.remove(mark) + + # we are now left with only duplicates in the list marks + duplicates = set(marks) + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have learnt + + * How to make sets from lists + * How to input sets + * How to perform union, intersection and symmectric difference operations + * How to check if a set is a subset of other + * The various similarities with lists like length and containership + +{{{ Show the "sponsored by FOSSEE" slide }}} + +#[Nishanth]: Will add this line after all of us fix on one. +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thankyou + diff -r 9bc78792904b -r 0ff3f1a97068 sets/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sets/slides.tex Fri Oct 08 11:32:09 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 9bc78792904b -r 0ff3f1a97068 tuples.rst --- a/tuples.rst Fri Oct 08 11:31:56 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,206 +0,0 @@ -Hello friends and welcome to the tutorial on Tuples - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall learn - - * what are tuples - * their similarities and dissimilarities with lists - * why are they needed - -Let`s get started by defining a tuple. A tuple is defined by enclosing -parantheses around a sequence of items seperated by commas. It is similar to -defining a list except that parantheses are used instead of square brackets. -:: - - t = (1, 2.5, "hello", -4, "world", 1.24, 5) - t - -defines a tuple. The items in the tuple are indexed using numbers and can be -accessed by using their position. -:: - - t[3] - -prints -4 which is the fourth item of the tuple. - -:: - - t[1:5:2] - -prints the corresponding slice - -This is the behaviour similar as to lists. But the difference can be seen when -we try to change an element in the tuple. -:: - - t[2] = "Hello" - -We can see that, it raises an error saying tuple does not support item -assignment. It only implies that tuples are immutable or in simple words, -tuples cannot be changed. - -But what is the use of tuples!!! - -We shall understand that soon. But let us look at a simple problem of swapping -values. - -{{{ Pause here and try out the following exercises }}} - -%% 1 %% a = 5 and b = 7. swap the values of a and b - -{{{ continue from paused state }}} -:: - - a = 5 - b = 7 - - a - b - -We define the two values -:: - - temp = a - a = b - b = temp - - a - b - -This is the traditional approach - -Now let us do it the python way -:: - - a - b - - a, b = b, a - - a - b - -We see that the values are swapped. -This idiom works for different datatypes also. -:: - - a = 2.5 - b = "hello" - - a - b - -Moreover this type of behaviour is straight forward and what you would expect -should happen naturally. - -This is possible because of the immutability of tuples. This process is called -tuple packing and unpacking. - -Let us first see what is tuple packing. Type -:: - - 5, - -What we see is a tuple with one element. -:: - - 5, "hello", 2.5 - -Now it is a tuple with two elements. - -So when we are actually typing two or more elements seperated by commas, those -elements are packed and a tuple is made from them. - -When you type -:: - - a, b = b, a - -First the values of b and a are packed into a tuple on the right side and then -unpacked into the variables a and b. - -Immutability of tuples ensures that the values are not changed during the -packing and unpacking. - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial. -we have learnt - - * How to define tuples - * The similarities of tuples with lists, like indexing and iterability - * The immutability of tuples - * The value swapping idiom in Python - * packing and unpacking of tuples - -{{{ Show the "sponsored by FOSSEE" slide }}} - -#[Nishanth]: Will add this line after all of us fix on one. -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thankyou - -.. Author : Nishanth - Internal Reviewer 1 : - Internal Reviewer 2 : - External Reviewer : - -Questions -========= - - 1. Define a tuple containing two values. The first being integer 4 and second - is a float 2.5 - - Answer: (4, 2.5) - - 2. If ``a = (5, "Hello", 3.2)``. what is the value of a[2] - - Answer: 3.2 - - 3. If ``a = 5,`` then what is the type of a - - a. int - #. float - #. tuple - #. string - - Answer: tuple - - 4. if ``a = (2, 3)``. What does ``a[0], a[1] = (3, 4)`` produce - - Answer: Error - - 5. If ``a = ([2, 3], 4, 5)``. What is the value of ``a`` after doing - ``a[0].append(6)`` - - a. ([2, 3, 6], 4, 5) - #. Raises an error - #. ([2, 3], 4, 5) - #. [2, 3, 4, 5, 6] - - Answer: ([2, 3, 6], 4, 5) - - 6. What does the following code produce:: - - a = 5 - b = "Hello" - a, b = b, a - print a - print b - - Answer: Hello - 5 - - 7. ``a = ("hello", "world", 5, 6, 8)``. What is the value of a[1:4] - - Answer: ("world", 5, 6) - - 8. ``a = (1, 2, 3, 4, 5, 6, 7, 8)``. What is the value of a[1::3] - - Answer: (2, 5, 8) - - diff -r 9bc78792904b -r 0ff3f1a97068 tuples/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tuples/questions.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,60 @@ +Objective Questions +------------------- + + 1. Define a tuple containing two values. The first being integer 4 and second + is a float 2.5 + + Answer: (4, 2.5) + + 2. If ``a = (5, "Hello", 3.2)``. what is the value of a[2] + + Answer: 3.2 + + 3. If ``a = 5,`` then what is the type of a + + a. int + #. float + #. tuple + #. string + + Answer: tuple + + 4. if ``a = (2, 3)``. What does ``a[0], a[1] = (3, 4)`` produce + + Answer: Error + + 5. If ``a = ([2, 3], 4, 5)``. What is the value of ``a`` after doing + ``a[0].append(6)`` + + a. ([2, 3, 6], 4, 5) + #. Raises an error + #. ([2, 3], 4, 5) + #. [2, 3, 4, 5, 6] + + Answer: ([2, 3, 6], 4, 5) + + 6. What does the following code produce:: + + a = 5 + b = "Hello" + a, b = b, a + print a + print b + + Answer:: + + Hello + 5 + + 7. ``a = ("hello", "world", 5, 6, 8)``. What is the value of a[1:4] + + Answer: ("world", 5, 6) + + 8. ``a = (1, 2, 3, 4, 5, 6, 7, 8)``. What is the value of a[1::3] + + Answer: (2, 5, 8) + + 9. ``a = (1, 2, 3, 4, 5, 6, 7, 8)``. What is the value of a[-3::-1] + + Answer: (6, 5, 4, 3, 2, 1) + diff -r 9bc78792904b -r 0ff3f1a97068 tuples/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tuples/quickref.tex Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,11 @@ +Creating a tuple:\\ +{\ex \lstinline| t = (1, "hello", 2.5)|} + +Accessing elements of tuples:\\ +{\ex \lstinline| t[index] Ex: t[2]|} + +Accessing slices of tuples:\\ +{\ex \lstinline| t[start:stop:step]|} + +Swapping values:\\ +{\ex \lstinline| a, b = b, a|} diff -r 9bc78792904b -r 0ff3f1a97068 tuples/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tuples/script.rst Fri Oct 08 11:32:09 2010 +0530 @@ -0,0 +1,168 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - Will learn what are tuples and why they are needed + Will learn the various methods of accessing elements in tuples + C - + D - + +.. Prerequisites +.. ------------- + +.. 1. Getting started with lists + +.. Author : Nishanth Amuluru + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +Hello friends and welcome to the tutorial on Tuples + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall learn + + * what are tuples + * their similarities and dissimilarities with lists + * why are they needed + +Let`s get started by defining a tuple. A tuple is defined by enclosing +parantheses around a sequence of items seperated by commas. It is similar to +defining a list except that parantheses are used instead of square brackets. +:: + + t = (1, 2.5, "hello", -4, "world", 1.24, 5) + t + +defines a tuple. The items in the tuple are indexed using numbers and can be +accessed by using their position. +:: + + t[3] + +prints -4 which is the fourth item of the tuple. + +:: + + t[1:5:2] + +prints the corresponding slice + +This is the behaviour similar as to lists. But the difference can be seen when +we try to change an element in the tuple. +:: + + t[2] = "Hello" + +We can see that, it raises an error saying tuple does not support item +assignment. It only implies that tuples are immutable or in simple words, +tuples cannot be changed. + +But what is the use of tuples!!! + +We shall understand that soon. But let us look at a simple problem of swapping +values. + +{{{ Pause here and try out the following exercises }}} + +%% 1 %% a = 5 and b = 7. swap the values of a and b + +{{{ continue from paused state }}} +:: + + a = 5 + b = 7 + + a + b + +We define the two values +:: + + temp = a + a = b + b = temp + + a + b + +This is the traditional approach + +Now let us do it the python way +:: + + a + b + + a, b = b, a + + a + b + +We see that the values are swapped. +This idiom works for different datatypes also. +:: + + a = 2.5 + b = "hello" + + a + b + +Moreover this type of behaviour is straight forward and what you would expect +should happen naturally. + +This is possible because of the immutability of tuples. This process is called +tuple packing and unpacking. + +Let us first see what is tuple packing. Type +:: + + 5, + +What we see is a tuple with one element. +:: + + 5, "hello", 2.5 + +Now it is a tuple with two elements. + +So when we are actually typing two or more elements seperated by commas, those +elements are packed and a tuple is made from them. + +When you type +:: + + a, b = b, a + +First the values of b and a are packed into a tuple on the right side and then +unpacked into the variables a and b. + +Immutability of tuples ensures that the values are not changed during the +packing and unpacking. + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have learnt + + * How to define tuples + * The similarities of tuples with lists, like indexing and iterability + * The immutability of tuples + * The value swapping idiom in Python + * packing and unpacking of tuples + +{{{ Show the "sponsored by FOSSEE" slide }}} + +#[Nishanth]: Will add this line after all of us fix on one. +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thankyou + diff -r 9bc78792904b -r 0ff3f1a97068 tuples/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tuples/slides.tex Fri Oct 08 11:32:09 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}