# HG changeset patch # User amit # Date 1286971379 -19800 # Node ID 4054b1a6392da437d6f5d5598459227ede3f288a # Parent e675f9208b91e8e5f4556d439b3921a0d37ad9c3# Parent e8c02b3c51aca4b45a260677014278d6288d4acf merging heads diff -r e675f9208b91 -r 4054b1a6392d accessing-pieces-arrays/quickref.tex --- a/accessing-pieces-arrays/quickref.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/accessing-pieces-arrays/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,8 +1,12 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} +\textbf{Accessing parts of arrays} + +\lstinline|C[i-1, j-1]| to access element i, j in C (mxn). +\lstinline|C[i-1]| to access i^{th} row +\lstinline|C[:, j-1]| to access j^{th} column -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} +Assigning to accessed elements, changes them. -Plotting two lists of equal length x, y:\\ -{\ex \lstinline| plot(x, y)|} +\lstinline|A[m:n:o]| accesses the rows from \lstinline|m| +to \lstinline|n| (excluded) in steps of \lstinline|o| + +Similarly, \lstinline|C[m:n:o, p:q:r]| diff -r e675f9208b91 -r 4054b1a6392d accessing-pieces-arrays/script.rst --- a/accessing-pieces-arrays/script.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/accessing-pieces-arrays/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,22 +1,21 @@ .. Objectives .. ---------- - By the end of this tutorial, you will be able to: + .. By the end of this tutorial, you will be able to: - 1. Access and change individual elements of arrays, both one - dimensional and multi-dimensional. - 2. Access and change rows and columns of arrays. - 3. Access and change other chunks from an array, using slicing - and striding. - 4. Read images into arrays and perform processing on them, using - simple array manipulations. + .. 1. Access and change individual elements of arrays, both one + .. dimensional and multi-dimensional. + .. 2. Access and change rows and columns of arrays. + .. 3. Access and change other chunks from an array, using slicing + .. and striding. + .. 4. Read images into arrays and perform processing on them, using + .. simple array manipulations. .. Prerequisites .. ------------- -.. 1. Name of LO-1 -.. 2. Name of LO-2 -.. 3. Name of LO-3 +.. 1. getting started with arrays + .. Author : Puneeth Internal Reviewer : @@ -299,8 +298,7 @@ Following is an exercise that you must do. -%%5%% Pause the video here, and obtain the square in the center -of the image. +%%5%% Obtain the square in the center of the image. Following is an exercise that you must do. diff -r e675f9208b91 -r 4054b1a6392d accessing-pieces-arrays/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/accessing-pieces-arrays/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,123 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Accessing parts of arrays +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Manipulating one and multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slicing and striding on arrays to access chunks + - Read images into arrays and manipulations +* Sample Arrays + #+begin_src python + In []: A = array([12, 23, 34, 45, 56]) + + In []: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) + + #+end_src +* Question 1 + Change the last column of ~C~ to zeroes. +* Solution 1 + #+begin_src python + In []: C[:, -1] = 0 + #+end_src +* Question 2 + Change ~A~ to ~[11, 12, 13, 14, 15]~. +* Solution 2 + #+begin_src python + In []: A[:] = [11, 12, 13, 14, 15] + #+end_src +* squares.png + #+begin_latex + \begin{center} + \includegraphics[scale=0.6]{squares} + \end{center} + #+end_latex +* Question 3 + - obtain ~[22, 23]~ from ~C~. + - obtain ~[11, 21, 31, 41]~ from ~C~. + - obtain ~[21, 31, 41, 0]~. +* Solution 3 + #+begin_src python + In []: C[1, 1:3] + In []: C[0:4, 0] + In []: C[1:5, 0] + #+end_src +* Question 4 + Obtain ~[[23, 24], [33, -34]]~ from ~C~ +* Solution 4 + #+begin_src python + In []: C[1:3, 2:4] + #+end_src +* Question 5 + Obtain the square in the center of the image +* Solution 5 + #+begin_src python + In []: imshow(I[75:225, 75:225]) + #+end_src +* Question 6 + Obtain the following + #+begin_src python + [[12, 0], [42, 0]] + [[12, 13, 14], [0, 0, 0]] + #+end_src + +* Solution 6 + #+begin_src python + In []: C[::3, 1::3] + In []: C[::4, 1:4] + #+end_src +* Summary + You should now be able to -- + - Manipulate 1D \& Multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slice and stride on arrays + - Read images into arrays and manipulate them. +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d accessing-pieces-arrays/slides.tex --- a/accessing-pieces-arrays/slides.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/accessing-pieces-arrays/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,95 +1,203 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{infolines} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} +% Created 2010-10-10 Sun 18:48 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{Accessing parts of arrays} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + \begin{frame} - \maketitle +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Manipulating one and multi dimensional arrays +\item Access and change individual elements +\item Access and change rows and columns +\item Slicing and striding on arrays to access chunks +\item Read images into arrays and manipulations +\end{itemize} \end{frame} +\begin{frame}[fragile] +\frametitle{Sample Arrays} +\label{sec-2} +\lstset{language=Python} +\begin{lstlisting} +In []: A = array([12, 23, 34, 45, 56]) + +In []: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-3} + + Change the last column of \texttt{C} to zeroes. +\end{frame} \begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 1} +\label{sec-4} + +\lstset{language=Python} +\begin{lstlisting} +In []: C[:, -1] = 0 +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-5} + + Change \texttt{A} to \texttt{[11, 12, 13, 14, 15]}. \end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-6} + +\lstset{language=Python} +\begin{lstlisting} +In []: A[:] = [11, 12, 13, 14, 15] +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{squares.png} +\label{sec-7} + + \begin{center} + \includegraphics[scale=0.6]{squares} + \end{center} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-8} + +\begin{itemize} +\item obtain \texttt{[22, 23]} from \texttt{C}. +\item obtain \texttt{[11, 21, 31, 41]} from \texttt{C}. +\item obtain \texttt{[21, 31, 41, 0]}. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 3} +\label{sec-9} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\lstset{language=Python} +\begin{lstlisting} +In []: C[1, 1:3] +In []: C[0:4, 0] +In []: C[1:5, 0] +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-10} + + Obtain \texttt{[[23, 24], [33, -34]]} from \texttt{C} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 4} +\label{sec-11} +\lstset{language=Python} +\begin{lstlisting} +In []: C[1:3, 2:4] +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 5} +\label{sec-12} + + Obtain the square in the center of the image +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 5} +\label{sec-13} + +\lstset{language=Python} +\begin{lstlisting} +In []: imshow(I[75:225, 75:225]) +\end{lstlisting} +\end{frame} \begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} +\frametitle{Question 6} +\label{sec-14} + + Obtain the following +\lstset{language=Python} +\begin{lstlisting} +[[12, 0], [42, 0]] +[[12, 13, 14], [0, 0, 0]] +\end{lstlisting} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 6} +\label{sec-15} + +\lstset{language=Python} +\begin{lstlisting} +In []: C[::3, 1::3] +In []: C[::4, 1:4] +\end{lstlisting} \end{frame} - \begin{frame} - \frametitle{Thank you!} +\frametitle{Summary} +\label{sec-16} + + You should now be able to -- +\begin{itemize} +\item Manipulate 1D \& Multi dimensional arrays + +\begin{itemize} +\item Access and change individual elements +\item Access and change rows and columns +\item Slice and stride on arrays +\end{itemize} + +\item Read images into arrays and manipulate them. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-17} + \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r e675f9208b91 -r 4054b1a6392d additional_ipython.rst --- a/additional_ipython.rst Wed Oct 13 17:32:23 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 e675f9208b91 -r 4054b1a6392d additional_ipython/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_ipython/questions.rst Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d additional_ipython/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_ipython/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,15 @@ +accessing history:\\ +{\ex \lstinline| \%hist|} + +accessing particular line of history:\\ +{\ex \lstinline| \%hist line_number|} + +accessing particular range of history:\\ +{\ex \lstinline| \%hist start_line stop_line|} + +saving history to a file:\\ +{\ex \lstinline| \%save file_path line_numbers|} + +running a script:\\ +{\ex \lstinline| \%run -i file_path|} + diff -r e675f9208b91 -r 4054b1a6392d additional_ipython/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_ipython/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,222 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - + C - + D - + +.. By the end of this tutorial you will be able to + +.. #. Retrieve your ipython history +.. #. View a part of the history +.. #. Save a part of your history to a file. +.. #. Run a script from within ipython + + +.. Prerequisites +.. ------------- + +.. 1. Embellishing Plots + +.. Author : Nishanth Amuluru + Internal Reviewer : + 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 documentation of %hist and find out how to + list all the commands between 5 and 10 + +{{{ continue from paused state }}} + +As we can see from =%hist= documentation, +:: + + %hist 5 10 + +displays the commands from 5 to 10 + +Now that we have the history, we would like to save the required line of code +from history. This is possible by using the =%save= command. + +Before we do that, let us first look at history and identify what lines of code +we require.Type +:: + + %hist + + +{{{ point to the lines }}} + +The first command is linspace. But second command is a command that gave us an +error. Hence we do not need 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. +Thank you! + diff -r e675f9208b91 -r 4054b1a6392d additional_ipython/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_ipython/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,90 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER:\usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Additional Features of =ipython= +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + + Retrieving ipython history + + Viewing a part of the history + + Saving (relevant) parts of the history to a file + + Running a script from within ipython +* Question 1 + Read through the documentation of ~%hist~ and find out how to list + all the commands between 5 and 10 +* Solution 1 + #+begin_src python + In []: %hist 5 10 + #+end_src +* Question 2 + Change the label on y-axis to "y" and save the lines of code + accordingly +* Solution 2 + #+begin_src python + In []: ylabel("y") + In []: %save /home/fossee/example_plot.py 1 3-6 10 + #+end_src +* Question 3 + Use =%hist= and =%save= and create a script that has show in it and + run it to produce and show the plot. + +* Solution 3 + #+begin_src python + In []: %hist 20 + + In []: %save /home/fossee/show_included.py 1 3-6 8 10 13 + In []: %run -i /home/fossee/show_included.py + #+end_src +* Question 4 + Run the script without using the -i option. Do you find any + difference? +* Solution 4 + We see that it raises ~NameError~ saying the name ~linspace~ is not + found. +* Summary + + Retreiving history using =%hist= command + + Vieweing only a part of history by passing an argument to %hist + + Saving the required lines of code in required order using %save + + Using %run -i command to run the saved script + +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d additional_ipython/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/additional_ipython/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,149 @@ +% Created 2010-10-10 Sun 17:30 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Additional Features of \texttt{ipython}} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Retrieving ipython history +\item Viewing a part of the history +\item Saving (relevant) parts of the history to a file +\item Running a script from within ipython +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Read through the documentation of \texttt{\%hist} and find out how to list + all the commands between 5 and 10 +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +In []: %hist 5 10 +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + Change the label on y-axis to ``y'' and save the lines of code + accordingly +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} + +\lstset{language=Python} +\begin{lstlisting} +In []: ylabel("y") +In []: %save /home/fossee/example_plot.py 1 3-6 10 +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + + Use \texttt{\%hist} and \texttt{\%save} and create a script that has show in it and + run it to produce and show the plot. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 3} +\label{sec-7} + +\lstset{language=Python} +\begin{lstlisting} +In []: %hist 20 + +In []: %save /home/fossee/show_included.py 1 3-6 8 10 13 +In []: %run -i /home/fossee/show_included.py +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-8} + + Run the script without using the -i option. Do you find any + difference? +\end{frame} +\begin{frame} +\frametitle{Solution 4} +\label{sec-9} + + We see that it raises \texttt{NameError} saying the name \texttt{linspace} is not + found. +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-10} + +\begin{itemize} +\item Retreiving history using \texttt{\%hist} command +\item Vieweing only a part of history by passing an argument to \%hist +\item Saving the required lines of code in required order using \%save +\item Using \%run -i command to run the saved script +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-11} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d advanced-features-functions/questions.rst --- a/advanced-features-functions/questions.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/advanced-features-functions/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,17 +1,109 @@ -Objective ---------- +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. All arguments of a function cannot have default values. True or + False? + + Answer: False + +#. When calling a function, the arguments + + 1. should always be in the order in which they are defined. + #. can be in any order + #. only keyword arguments can be in any order, but should be called + at the beginning. + #. only keyword arguments can be in any order, but should be called + at the end. + + Answer: only keyword arguments can be in any order, but should be called + at the end. -.. A mininum of 8 questions here. +#. Given the following function, identify the keywords with default + values. + :: + + def seperator(char, count=40, show=False): + + if show: + print char * count + + return char * count + + Answer: ``count``, ``show`` -1. Question 1 -2. Question 2 -3. Question 3 +#. Given the following function, + :: + + def seperator(char, count=40, show=False): + + if show: + print char * count + + return char * count + + What is the output of ``separator("+", 1, True)``. + + Answer: ``+`` is printed and returned. -Programming ------------ +#. Given the following function, + :: + + def seperator(char, count=40, show=False): + + if show: + print char * count + + return char * count + + What is the output of ``separator("+", True, 1)``. + + Answer: ``+`` is printed and returned. + +#. Given the following function, + :: + + def seperator(char, count=40, show=False): + + if show: + print char * count + + return char * count + + What is the output of ``separator("+", show=True, 1)``. + + Answer: SyntaxError -.. A minimum of 2 questions here. +#. The following is a valid function definition. True or False? Why? + :: + + def seperator(count=40, char, show=False): + + if show: + print char * count + + return char * count + + Answer: False. All parameters with default arguments should be + defined at the end. -1. Programming Assignment 1 -2. Programming Assignment 2 +#. Which of the following cannot be used as default values for + arguments? + + a. floats + #. lists + #. functions + #. booleans + #. None of the Above + + Answer: None of the above. + + +Larger Questions +---------------- + +1. + +2. diff -r e675f9208b91 -r 4054b1a6392d advanced-features-functions/quickref.tex --- a/advanced-features-functions/quickref.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/advanced-features-functions/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,8 +1,8 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} +\textbf{Advanced features of functions} + +Arguments of functions can have default arguments. -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} +All arguments with default arguments are at the end of the definition. -Plotting two lists of equal length x, y:\\ -{\ex \lstinline| plot(x, y)|} +Functions can be called with keyword arguments. All the keyword +arguments should be at the end of the argument list. diff -r e675f9208b91 -r 4054b1a6392d advanced-features-functions/script.rst --- a/advanced-features-functions/script.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/advanced-features-functions/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,17 +1,40 @@ -======== - Script -======== +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Assign default values to arguments, when defining functions +.. 2. Define and call functions with keyword arguments. +.. 3. Also, you will get a glimpse of the plethora of functions +.. available, in Python standard library and the scientific computing +.. libraries. + -{{{ show the welcome slide }}} +.. Prerequisites +.. ------------- + +.. 1. getting started with ipython +.. #. getting started with functions + +.. Author : Puneeth + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +{{{ Show the slide containing title }}} Welcome to the tutorial on advanced feature of functions. -{{{ show the outline slide }}} +{{{ Show the outline slide }}} In this tutorial we shall be looking at specifying default arguments to functions when defining them and calling functions using keyword arguments. We shall also, look at some of the built-in functions -available in the standard library of Python. +available in the standard library of Python and the scientific +computing libraries. {{{ switch to terminal }}} @@ -46,7 +69,7 @@ linspace(0, 2*pi, 100) # returns 100 points between 0 and 2pi linspace(0, 2*pi) # returns 50 points between 0 and 2pi -#[punch: all above content goes on to a slide] +.. #[punch: all above content goes on to a slide] {{{ switch back to ipython }}} @@ -76,10 +99,13 @@ "Hello" is treated as the ``greet`` and we get "Hello World" as the output. "World" is the default value for the argument ``name``. -E%% %% Pause the video here and redefine the function ``welcome``, by -interchanging it's arguments. Place the ``name`` argument with it's -default value of "Hello" before the ``greet`` argument. Then, resume -the video. +Following is an (are) exercise(s) that you must do. + +%%1%% Redefine the function ``welcome``, by interchanging it's +arguments. Place the ``name`` argument with it's default value of +"World" before the ``greet`` argument. + +Please, pause the video here. Do the exercise and then continue. :: @@ -90,17 +116,24 @@ default argument``. When defining a function all the argument with default values should come at the end. -E%% %% Pause the video here and type ``linspace?`` to see the -definition of the command and notice how all the arguments with -default values are towards the end. +Following is an exercise that you must do. + +%%2%% See the definition of linspace using ``?`` and observe how all +the arguments with default values are towards the end. + +Please, pause the video here. Do the exercise and then continue. :: linspace? -E%% %% Pause the video here and redefine the function ``welcome`` with -a default value of "Hello" to the ``greet`` argument. Then, call the -function without any arguments. Then, resume the video. +Following is an exercise that you must do. + +%%3%% Redefine the function ``welcome`` with a default value of +"Hello" to the ``greet`` argument. Then, call the function without any +arguments. + +Please, pause the video here. Do the exercise and then continue. :: @@ -109,7 +142,7 @@ welcome() - + Let us now learn what keyword arguments are. @@ -175,8 +208,8 @@ Math functions - abs, sin, .... -#[punch: Need to decide, exactly what to put here. Reviewer comments - welcome.] +.. #[punch: Need to decide, exactly what to put here. Reviewer comments +.. welcome.] {{{ switch to slide showing classes of functions in pylab, scipy }}} @@ -192,7 +225,7 @@ scipy (modules) fftpack, stats, linalg, ndimage, signal, optimize, integrate -{{{ switch slide to summary slide }}} +{{{ Show summary slide }}} That brings us to the end of this tutorial. In this tutorial we have learnt how to use functions with default values and keyword @@ -200,4 +233,9 @@ Python standard library and the Scientific Computing related packages. -Thank You! +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you! diff -r e675f9208b91 -r 4054b1a6392d advanced-features-functions/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/advanced-features-functions/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,86 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Advanced features of functions +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Assigning default values to arguments + - Calling functions using Keyword arguments + - functions in standard library +* Question 1 + Redefine the function ~welcome~, by interchanging it's + arguments. Place the ~name~ argument with it's default value of + "World" before the ~greet~ argument. +* Solution 1 + #+begin_src python + def welcome(name="World", greet): + print greet, name + #+end_src + We get an error that reads ~SyntaxError: non-default argument + follows default argument~. When defining a function all the + argument with default values should come at the end. + +* Question 2 + See the definition of linspace using ~?~ and observe how all the + arguments with default values are towards the end. +* Solution 2 + #+begin_src python + linspace? + #+end_src +* Question 3 + Redefine the function ~welcome~ with a default value of + "Hello" to the ~greet~ argument. Then, call the function without any + arguments. +* Solution 3 + #+begin_src python + def welcome(greet="Hello", name="World"): + print greet, name + + welcome() + #+end_src +* Summary + You should now be able to -- + + define functions with default arguments + + call functions using keyword arguments +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d advanced-features-functions/slides.tex --- a/advanced-features-functions/slides.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/advanced-features-functions/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,95 +1,125 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{infolines} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} +% Created 2010-10-11 Mon 00:34 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{Advanced features of functions} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + \begin{frame} - \maketitle +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Assigning default values to arguments +\item Calling functions using Keyword arguments +\item functions in standard library +\end{itemize} \end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + Redefine the function \texttt{welcome}, by interchanging it's + arguments. Place the \texttt{name} argument with it's default value of + ``World'' before the \texttt{greet} argument. +\end{frame} \begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +def welcome(name="World", greet): + print greet, name +\end{lstlisting} + We get an error that reads \texttt{SyntaxError: non-default argument follows default argument}. When defining a function all the + argument with default values should come at the end. \end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + See the definition of linspace using \texttt{?} and observe how all the + arguments with default values are towards the end. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\lstset{language=Python} +\begin{lstlisting} +linspace? +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + Redefine the function \texttt{welcome} with a default value of + ``Hello'' to the \texttt{greet} argument. Then, call the function without any + arguments. +\end{frame} \begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 3} +\label{sec-7} + +\lstset{language=Python} +\begin{lstlisting} +def welcome(greet="Hello", name="World"): + print greet, name + +welcome() +\end{lstlisting} \end{frame} - \begin{frame} - \frametitle{Thank you!} +\frametitle{Summary} +\label{sec-8} + + You should now be able to -- +\begin{itemize} +\item define functions with default arguments +\item call functions using keyword arguments +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-9} + \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r e675f9208b91 -r 4054b1a6392d conditionals.rst --- a/conditionals.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,176 +0,0 @@ -Hello friends. Welcome to this spoken tutorial on Getting started with -strings. - -{{{ Show the slide containing the title }}} - -{{{ Show the slide containing the outline }}} - -In this tutorial, we will learn the basic conditional constructs -available in Python. We learn the if/else, if/elif/else and ternary -conditional constructs available in Python. - -{{{ Shift to terminal and start ipython }}} - -To begin with let us start ipython, by typing:: - - ipython - -on the terminal - -Whenever we have two possible states that can occur depending on a -whether a certain condition we can use if/else construct in -Python. Say for example we have a variable "a" which stores integers -and we are required to find out whether the value of the variable "a" -is an even number or an odd number. To test out conditional statements -as an example, let us say the value of the variable "a" is 5:: - - a = 5 - -In such a case we can write the if/else block as:: - - if a % 2 == 0: - print "Even" - else: - print "Odd" - -When the value of the variable "a" is divided by 2 and the remainder -is 0 i.e. the result of the operation "a modulo 2" is 0 the condition -"a % 2 == 0" evaluates to True, so the code within the if block gets -executed. This means that the value of "a" is Even. - -If the operation "a modulo 2" is not 0 the condition "a % 2 == 0" -evaluates to False and hence the code block within else gets executed -which means that the value of "a" is Odd. - -Note in such a case only one of the two blocks get executed depending -on whether the condition is True or False. - -There is a very important sytactic element to understand here. All the -statements which are inside a certain code block are indented by 4 -spaces. The statement which starts a new code block after it, i.e. the -if statement in this example ends with a colon (:). So the next -immediate line will be inside the if block and hence indented by 4 -spaces. To come out of the code block we have to come back to the -previous indentation level as shown in the else line here. Again the -line following else will be in a new block so else line ends with a -colon and the following block of code is indented by 4. - -As we use if/else statement when we have a condition which can take -one of the two states, we may have conditions which can take more than -two states. In such a scenario Python provides if/elif/else -statements. Let us take an example. We have a variable "a" which holds -integer values. We need to print "positive" if the value of a is -positive, "negative" if it is negative and "zero" if the value of the -variable "a" is 0. Let us use if/elif/else ladder for it. For the -purposes of testing our code let us assume that the value of a is -3:: - - a = -3 - - if a > 0: - print "positive" - elif a < 0: - print "negative" - else: - print "zero" - -This if/elif/else ladder is self explanatory. All the syntax and rules -as said for if/else statements hold. The only addition here is the -elif statement which can have another condition of its own. - -Here, exactly one block of code is executed and that block of code -corresponds to the condition which first evaluates to True. Even if -there is a situation where multiple conditions evaluate to True all -the subsequent conditions other than the first one which evaluates to -True are neglected. Consequently, the else block gets executed if and -only if all the conditions evaluate to False. - -Also, the else block in both if/else statement and if/elif/else is -optional. We can have a single if statement or just if/elif statements -without having else block at all. Also, there can be any number of -elif's within an if/elif/else ladder. For example - -{{{ Show slide for this }}} - - if user == 'admin': - # Do admin operations - elif user == 'moderator': - # Do moderator operations - elif user == 'client': - # Do customer operations - -{{{ end of slide switch to ipython }}} - -is completely valid. Note that there are multiple elif blocks and there -is no else block. - -In addition to these conditional statements, Python provides a very -convenient ternary conditional operator. Let us take the following -example where we read the marks data from a data file which is -obtained as a string as we read a file. The marks can be in the range -of 0 to 100 or 'AA' if the student is absent. In such a case to obtain -the marks as an integer we can use the ternary conditional -operator. Let us say the string score is stored in score_str -variable:: - - score_str = 'AA' - -Now let us use the ternary conditional operator:: - - score = int(score_str) if score_str != 'AA' else 0 - -This is just the if/else statement block which written in a more -convenient form and is very helpful when we have only one statement -for each block. This conditional statement effectively means as we -would have exactly specified in the English language which will be -like score is integer of score_str is score_str is not 'AA' otherwise -it is 0. This means that we make the scores of the students who were -absent for the exam 0. - -Moving on, there are certain situations where we will have to no -operations or statements within the block of code. For example, we -have a code where we are waiting for the keyboard input. If the user -enters "s" as the input we would perform some operation nothing -otherwise. In such cases "pass" statement comes very handy:: - - a = raw_input("Enter 'c' to calculate and exit, 'd' to display the existing - results exit and 'x' to exit and any other key to continue: ") - - if a == 'c': - # Calculate the marks and exit - elif a == 'd': - # Display the results and exit - elif a == 'x': - # Exit the program - else: - pass - -In this case "pass" statement acts as a place holder for the block of -code. It is equivalent to a null operation. It literally does -nothing. So "pass" statement can be used as a null operation -statement, or it can used as a place holder when the actual code -implementation for a particular block of code is not known yet but has -to be filled up later. - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial session on conditional -statements in Python. In this tutorial session we learnt - - * What are conditional statements - * if/else statement - * if/elif/else statement - * Ternary conditional statement - C if X else Y - * and the "pass" statement - -{{{ Show the "sponsored by FOSSEE" slide }}} - -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thankyou - -.. Author : Madhu - Internal Reviewer 1 : [potential reviewer: Puneeth] - Internal Reviewer 2 : [potential reviewer: Anoop] - External Reviewer : - diff -r e675f9208b91 -r 4054b1a6392d conditionals/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conditionals/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,79 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Given a variable ``time``, print ``Good Morning`` if it is less + than 12, otherwise ``Hello``. + + Answer:: + + if time < 12: + print "Good Morning" + + else: + print "Hello" + +#. Every ``if`` block must be followed by an ``else`` block. T or F? + + Answer: F + +#. Every ``if/elif/else`` ladder MUST end with an ``else`` block. T/F? + + Answer: F + +#. An if/elif/else ladder can have any number of elif blocks. T or F? + + Answer: T + +#. What will be printed at the end this code block:: + + x = 20 + + if x > 10: + print x * 100 + + Answer: IndentationError - Expected and indented block.. + +#. What will be printed at the end this code block:: + + x = 20 + + if x > 10: + print x * 100 + else: + print x + + Answer: SyntaxError + +#. What will be printed at the end this code block:: + + x = 20 + + if x > 10: + print x * 100 + else: + print x + + Answer: 2000 + +#. Convert the if else ladder below into a ternary conditional + statement:: + + x = 20 + + if x > 10: + print x * 100 + else: + print x + + Answer: print x * 100 if x > 10 else x + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Question 1 +2. Question 2 diff -r e675f9208b91 -r 4054b1a6392d conditionals/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conditionals/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,8 @@ +Creating a linear array:\\ +{\ex \lstinline| x = linspace(0, 2*pi, 50)|} + +Plotting two variables:\\ +{\ex \lstinline| plot(x, sin(x))|} + +Plotting two lists of equal length x, y:\\ +{\ex \lstinline| plot(x, y)|} diff -r e675f9208b91 -r 4054b1a6392d conditionals/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conditionals/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,192 @@ +.. Objectives +.. ---------- + +.. Clearly state the objectives of the LO (along with RBT level) + +.. Prerequisites +.. ------------- + +.. 1. Name of LO-1 +.. 2. Name of LO-2 +.. 3. Name of LO-3 + +.. Author : Madhu + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + + +Script +------ + +{{{ Show the slide containing the title }}} + +Hello friends. Welcome to this spoken tutorial on Getting started with +strings. + +{{{ Show the slide containing the outline }}} + +In this tutorial, we will learn the basic conditional constructs +available in Python. We learn the if/else, if/elif/else and ternary +conditional constructs available in Python. + +{{{ Shift to terminal and start ipython }}} + +To begin with let us start ipython, by typing:: + + ipython + +on the terminal + +Whenever we have two possible states that can occur depending on a +whether a certain condition we can use if/else construct in +Python. Say for example we have a variable "a" which stores integers +and we are required to find out whether the value of the variable "a" +is an even number or an odd number. To test out conditional statements +as an example, let us say the value of the variable "a" is 5:: + + a = 5 + +In such a case we can write the if/else block as:: + + if a % 2 == 0: + print "Even" + else: + print "Odd" + +When the value of the variable "a" is divided by 2 and the remainder +is 0 i.e. the result of the operation "a modulo 2" is 0 the condition +"a % 2 == 0" evaluates to True, so the code within the if block gets +executed. This means that the value of "a" is Even. + +If the operation "a modulo 2" is not 0 the condition "a % 2 == 0" +evaluates to False and hence the code block within else gets executed +which means that the value of "a" is Odd. + +Note in such a case only one of the two blocks get executed depending +on whether the condition is True or False. + +There is a very important sytactic element to understand here. All the +statements which are inside a certain code block are indented by 4 +spaces. The statement which starts a new code block after it, i.e. the +if statement in this example ends with a colon (:). So the next +immediate line will be inside the if block and hence indented by 4 +spaces. To come out of the code block we have to come back to the +previous indentation level as shown in the else line here. Again the +line following else will be in a new block so else line ends with a +colon and the following block of code is indented by 4. + +As we use if/else statement when we have a condition which can take +one of the two states, we may have conditions which can take more than +two states. In such a scenario Python provides if/elif/else +statements. Let us take an example. We have a variable "a" which holds +integer values. We need to print "positive" if the value of a is +positive, "negative" if it is negative and "zero" if the value of the +variable "a" is 0. Let us use if/elif/else ladder for it. For the +purposes of testing our code let us assume that the value of a is -3:: + + a = -3 + + if a > 0: + print "positive" + elif a < 0: + print "negative" + else: + print "zero" + +This if/elif/else ladder is self explanatory. All the syntax and rules +as said for if/else statements hold. The only addition here is the +elif statement which can have another condition of its own. + +Here, exactly one block of code is executed and that block of code +corresponds to the condition which first evaluates to True. Even if +there is a situation where multiple conditions evaluate to True all +the subsequent conditions other than the first one which evaluates to +True are neglected. Consequently, the else block gets executed if and +only if all the conditions evaluate to False. + +Also, the else block in both if/else statement and if/elif/else is +optional. We can have a single if statement or just if/elif statements +without having else block at all. Also, there can be any number of +elif's within an if/elif/else ladder. For example + +{{{ Show slide for this }}} + + if user == 'admin': + # Do admin operations + elif user == 'moderator': + # Do moderator operations + elif user == 'client': + # Do customer operations + +{{{ end of slide switch to ipython }}} + +is completely valid. Note that there are multiple elif blocks and there +is no else block. + +In addition to these conditional statements, Python provides a very +convenient ternary conditional operator. Let us take the following +example where we read the marks data from a data file which is +obtained as a string as we read a file. The marks can be in the range +of 0 to 100 or 'AA' if the student is absent. In such a case to obtain +the marks as an integer we can use the ternary conditional +operator. Let us say the string score is stored in score_str +variable:: + + score_str = 'AA' + +Now let us use the ternary conditional operator:: + + score = int(score_str) if score_str != 'AA' else 0 + +This is just the if/else statement block which written in a more +convenient form and is very helpful when we have only one statement +for each block. This conditional statement effectively means as we +would have exactly specified in the English language which will be +like score is integer of score_str is score_str is not 'AA' otherwise +it is 0. This means that we make the scores of the students who were +absent for the exam 0. + +Moving on, there are certain situations where we will have to no +operations or statements within the block of code. For example, we +have a code where we are waiting for the keyboard input. If the user +enters "s" as the input we would perform some operation nothing +otherwise. In such cases "pass" statement comes very handy:: + + a = raw_input("Enter 'c' to calculate and exit, 'd' to display the existing + results exit and 'x' to exit and any other key to continue: ") + + if a == 'c': + # Calculate the marks and exit + elif a == 'd': + # Display the results and exit + elif a == 'x': + # Exit the program + else: + pass + +In this case "pass" statement acts as a place holder for the block of +code. It is equivalent to a null operation. It literally does +nothing. So "pass" statement can be used as a null operation +statement, or it can used as a place holder when the actual code +implementation for a particular block of code is not known yet but has +to be filled up later. + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial session on conditional +statements in Python. In this tutorial session we learnt + + * What are conditional statements + * if/else statement + * if/elif/else statement + * Ternary conditional statement - C if X else Y + * and the "pass" statement + +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you! + diff -r e675f9208b91 -r 4054b1a6392d conditionals/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conditionals/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,123 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Accessing parts of arrays +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Manipulating one and multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slicing and striding on arrays to access chunks + - Read images into arrays and manipulations +* Sample Arrays + #+begin_src python + In []: A = array([12, 23, 34, 45, 56]) + + In []: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) + + #+end_src +* Question 1 + Change the last column of ~C~ to zeroes. +* Solution 1 + #+begin_src python + In []: C[:, -1] = 0 + #+end_src +* Question 2 + Change ~A~ to ~[11, 12, 13, 14, 15]~. +* Solution 2 + #+begin_src python + In []: A[:] = [11, 12, 13, 14, 15] + #+end_src +* squares.png + #+begin_latex + \begin{center} + \includegraphics[scale=0.6]{squares} + \end{center} + #+end_latex +* Question 3 + - obtain ~[22, 23]~ from ~C~. + - obtain ~[11, 21, 31, 41]~ from ~C~. + - obtain ~[21, 31, 41, 0]~. +* Solution 3 + #+begin_src python + In []: C[1, 1:3] + In []: C[0:4, 0] + In []: C[1:5, 0] + #+end_src +* Question 4 + Obtain ~[[23, 24], [33, -34]]~ from ~C~ +* Solution 4 + #+begin_src python + In []: C[1:3, 2:4] + #+end_src +* Question 5 + Obtain the square in the center of the image +* Solution 5 + #+begin_src python + In []: imshow(I[75:225, 75:225]) + #+end_src +* Question 6 + Obtain the following + #+begin_src python + [[12, 0], [42, 0]] + [[12, 13, 14], [0, 0, 0]] + #+end_src + +* Solution 6 + #+begin_src python + In []: C[::3, 1::3] + In []: C[::4, 1:4] + #+end_src +* Summary + You should now be able to -- + - Manipulate 1D \& Multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slice and stride on arrays + - Read images into arrays and manipulate them. +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d conditionals/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/conditionals/slides.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d dictionaries.rst --- a/dictionaries.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,177 +0,0 @@ -.. 8.4 LO: dictionaries (2) -.. ------------------------ -.. * empty -.. * filled -.. * accessing via keys -.. * .values(), .keys() -.. * in -.. * iteration - -============ -Dictionaries -============ - -{{{ show the welcome slide }}} - -Welcome to the spoken tutorial on dictionaries. - -{{{ switch to next slide, outline slide }}} - -In this tutorial, we will see how to create empty dictionaries, learn -about keys and values of dictionaries. Checking for elements and -iterating over elements. - -{{{ switch to next slide on overview of dictionaries }}} - -A dictionary in general, is designed to look up meanings of -words. Similarly, Python dictionary is also designed to look up for a -specific key and retrieve the corresponding value. Dictionaries are -data structures that provide key-value mappings. Dictionaries are -similar to lists except that instead of the values having integer -indexes, dictionaries have keys or strings as indexes. - -Before we can proceed, start your IPython interpreter with the -``-pylab`` option. - -{{{ start ipython interpreter by issuing command ipython -pylab }}} - -Let us start by creating an empty dictionary, type the following in -your IPython interpreter. -:: - - mt_dict = {} - -Notice that unlike lists curly braces are used define ``dictionary``, - -{{{ move the mouse over curly braces to grab attention }}} - -Now let us see how to create a filled dictionary, -:: - - extensions = {'jpg' : 'JPEG Image', 'py' : 'Python script', 'html' : 'Html document', 'pdf' : 'Portable Document Format'} - -Notice that each key-value pair is separated by a comma - -{{{ move the mouse over the commas to grab attention }}} - -and each key and value are separated using a colon. - -{{{ move the mouse over the colon one by one to grab attention }}} - -Here, we defined four entries in the dictionary extensions. The keys -are - -{{{ spell the keys letter by letter }}} - -jpg, py, html, and pdf. - -Simply type, -:: - - extensions - -in the interpreter to see the content of the dictionary. Notice that -in dictionaries the order cannot be predicted and you can see that the -values are not in the order that we entered in. - -Like in lists, the elements in a dictionary can be accessed using the -index, here the index is the key. Try, -:: - - print extensions['jpg'] - -It printed JPEG Image. And now try, -:: - - print extensions['zip'] - -Well it gave us an error, saying that the key 'zip' is not in the -dictionary. - -Pause here for some time and try few more keys. Also try jpg in -capital letters. - -{{{ switch to next slide, adding and deleting keys and values in -dictionaries }}} - -Well that was about creating dictionaries, now how do we add or delete -items. We can add new items into dictionaries as, -:: - - extensions['cpp'] = 'C++ code' - -and delete items using the ``del`` keyword as, -:: - - del extension['pdf'] - -Let us check the content of the dictionary now, -:: - - extensions - -So the changes have been made. Now let us try one more thing, -:: - - extensions['cpp'] = 'C++ source code' - extensions - -As you can see, it did not add a new thing nor gave an error, but it -simply replaces the existing value with the new one. - -Now let us learn how to check if a particular key is present in the -dictionary. For that we can use ``in``, -:: - - 'py' in extensions - 'odt' in extensions - -So in short it will return ``True`` if the key is found in the -dictionary, and will return ``False`` if key is not present. Note that -we can check only for container-ship of keys in dictionaries and not -values. - -{{{ switch to next slide, Retrieve keys and values }}} - -Now let us see how to retrieve the keys and values. We can use the -method ``keys()`` for getting a list of the keys in a particular -dictionary and the method ``values()`` for getting a list of -values. Let us try them, -:: - - extensions.keys() - -It returned the ``list`` of keys in the dictionary extensions. And now -the other one, -:: - - extensions.values() - -It returned the ``list`` of values in the dictionary. - -{{{ switch to next slide, problem statement for the next solved -exercise }}} - -Now let us try to print the data in the dictionary. We can use ``for`` -loop to iterate. -:: - - for each in extensions.keys(): - print each, "-->", extensions[each] - - -{{{ switch to next slide, recap }}} - -This brings us to the end of this tutorial, we learned dictionaries -and saw how to create an empty dictionary, build a dictionary with -some data in it, adding data, ``keys()`` and ``values()`` methods, and -iterating over the dictionaries. - -{{{ switch to next slide, thank you slide }}} - -Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: diff -r e675f9208b91 -r 4054b1a6392d dictionaries/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dictionaries/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,102 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Container-ship of values can be checked in a python dictionary + + a. True + #. False + +Answer: False + +2. Container-ship of only keys can be checked in a python dictionary + + a. True + #. False + +Answer: True + +3. The value in a dictionary can be + + a. String + #. Integer + #. Any data type + #. None + +Answer: Any data type + +4. Python lists can be made as a key in dictionaries. + + a. True + #. False + +Answer: False + +5. Given a python dictionary ``x = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : + 4}``. When printed using ``print x`` will generate the output in + the order. {key-value pair ``'a':1`` identified as a, ``'b':2`` + identified as b and so on} + + a. a, b, c, d + #. d, c, b, a + #. a, c, b, d + #. b, d, a, c + #. Cannot predict + +Answer: Cannot predict + +6. The python dictionary ``x = {'a' : ['a', 'b', 'c'], 'b' : (1, 2, 3), + 1 : {1 : 'one', 2 : 'two'}, 10 : {10 : 'ten', 11 : 'eleven'}}`` is + invalid. + + a. True + #. False + +Answer: False + +7. Consider the python dictionary ``x = {'a' : ['a','b','c'], 'b' : + (1, 2, 3), 1 : {1 : 'one', 2 : 'two'}, 10 : {10 : 'ten', 11 : + 'eleven'}}``. And after applying the code below, what will be the + output of ``print x['a']`` + :: + + x['a'].extend(['d', 'e']) + x['a'][3] = x[10] + + a. Code will result in error + #. ['a', 'b', 'c', {11: 'eleven', 10: 'ten'}, 'e'] + #. {10 : 'ten', 11 : 'eleven'} + #. {10 : 'ten', 11 : 'eleven', 'a' : ['a', 'b', 'c']} + #. (1, 2, 3, ['a', 'b', 'c']) + +Answer: ['a', 'b', 'c', {11: 'eleven', 10: 'ten'}, 'e'] + +8. Consider the python dictionary ``x = {'a' : ['a','b','c'], 'b' : + (1, 2, 3), 1 : {1 : 'one', 2 : 'two'}, 10 : {10 : 'ten', 11 : + 'eleven'}}``. The code ``(1, 2, 3) in x.values()`` will return + + a. True + #. False + #. Container-ship of values cannot be checked in dictionaries + #. The dictionary is invalid + +Answer: True + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Write a python script which can print the numbers from 1 to + 999(both included) in words. + +2. Given the list of marks of students in a class, write a program to + find the duplicate marks. List the duplicate marks and also print + the number of duplicates for each. + +3. Given a list of words, find the anagrams in it and list them. + [meats, tap, steep, tames, hare, pets, had, apt, teams, dark, + dealer, once, rhea, cloud, step, steam, have, could, ounce, pest, + head, leader, cone, rare, rear, hear, pat, mates] + diff -r e675f9208b91 -r 4054b1a6392d dictionaries/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dictionaries/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,194 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Create dictionaries +.. #. Add data to dictionaries +.. #. Retrieve data +.. #. Familiarize using ``.keys()`` and ``.values()`` methods +.. #. Checking for container-ship of keys +.. #. Iterating over elements + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` installed. +.. #. getting started with ``ipython``. +.. #. basic datatypes. + +.. Author : Anoop Jacob Thomas + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + + +============ +Dictionaries +============ + +{{{ show the welcome slide }}} + +Welcome to the spoken tutorial on dictionaries. + +{{{ switch to next slide, outline slide }}} + +In this tutorial, we will see how to create empty dictionaries, learn +about keys and values of dictionaries. Checking for elements and +iterating over elements. + +{{{ switch to next slide on overview of dictionaries }}} + +A dictionary in general, is designed to look up meanings of +words. Similarly, Python dictionary is also designed to look up for a +specific key and retrieve the corresponding value. Dictionaries are +data structures that provide key-value mappings. Dictionaries are +similar to lists except that instead of the values having integer +indexes, dictionaries have keys or strings as indexes. + +Before we can proceed, start your IPython interpreter with the +``-pylab`` option. + +{{{ start ipython interpreter by issuing command ipython -pylab }}} + +{{{ switch to next slide, Creating dictionary }}} + +Let us start by creating an empty dictionary, type the following in +your IPython interpreter. +:: + + mt_dict = {} + +Notice that unlike lists curly braces are used define ``dictionary``, + +{{{ move the mouse over curly braces to grab attention }}} + +Now let us see how to create a filled dictionary, +:: + + extensions = {'jpg' : 'JPEG Image', 'py' : 'Python script', 'html' : 'Html document', 'pdf' : 'Portable Document Format'} + +Notice that each key-value pair is separated by a comma + +{{{ move the mouse over the commas to grab attention }}} + +and each key and value are separated using a colon. + +{{{ move the mouse over the colon one by one to grab attention }}} + +Here, we defined four entries in the dictionary extensions. The keys +are + +{{{ spell the keys letter by letter }}} + +jpg, py, html, and pdf. + +Simply type, +:: + + extensions + +in the interpreter to see the content of the dictionary. Notice that +in dictionaries the order cannot be predicted and you can see that the +values are not in the order that we entered in. + +{{{ switch to next slide, accessing elements }}} + +Like in lists, the elements in a dictionary can be accessed using the +index, here the index is the key. Try, +:: + + print extensions['jpg'] + +It printed JPEG Image. And now try, +:: + + print extensions['zip'] + +Well it gave us an error, saying that the key 'zip' is not in the +dictionary. + +Pause here for some time and try few more keys. Also try jpg in +capital letters. + +{{{ switch to next slide, adding and deleting keys and values in +dictionaries }}} + +Well that was about creating dictionaries, now how do we add or delete +items. We can add new items into dictionaries as, +:: + + extensions['cpp'] = 'C++ code' + +and delete items using the ``del`` keyword as, +:: + + del extension['pdf'] + +Let us check the content of the dictionary now, +:: + + extensions + +So the changes have been made. Now let us try one more thing, +:: + + extensions['cpp'] = 'C++ source code' + extensions + +As you can see, it did not add a new thing nor gave an error, but it +simply replaces the existing value with the new one. + +Now let us learn how to check if a particular key is present in the +dictionary. For that we can use ``in``, +:: + + 'py' in extensions + 'odt' in extensions + +So in short it will return ``True`` if the key is found in the +dictionary, and will return ``False`` if key is not present. Note that +we can check only for container-ship of keys in dictionaries and not +values. + +{{{ switch to next slide, Retrieve keys and values }}} + +Now let us see how to retrieve the keys and values. We can use the +method ``keys()`` for getting a list of the keys in a particular +dictionary and the method ``values()`` for getting a list of +values. Let us try them, +:: + + extensions.keys() + +It returned the ``list`` of keys in the dictionary extensions. And now +the other one, +:: + + extensions.values() + +It returned the ``list`` of values in the dictionary. + +{{{ switch to next slide, problem statement for the next solved +exercise }}} + +Now let us try to print the data in the dictionary. We can use ``for`` +loop to iterate. Pause here and try to do it yourself. + +It can be solved as, +:: + + for each in extensions.keys(): + print each, "-->", extensions[each] + + +{{{ switch to next slide, summary }}} + +This brings us to the end of this tutorial, we learned dictionaries +and saw how to create an empty dictionary, build a dictionary with +some data in it, adding data, ``keys()`` and ``values()`` methods, and +iterating over the dictionaries. + +{{{ switch to next slide, thank you slide }}} + +Thank you! diff -r e675f9208b91 -r 4054b1a6392d dictionaries/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dictionaries/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,117 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Dictionaries +#+AUTHOR: FOSSEE +#+EMAIL: info@fossee.in +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Creating dictionaries + - empty dictionaries + - with data + - Keys and values + - Checking for elements + - Iterating over elements + +* Overview of Dictionaries + - A dictionary contains meaning of words + - /Word/ is the /key/ here. + - /Meaning/ is the /value/ here. + - A Key-Value pair data structure + - Provide key-value mappings + +* Creating dictionary + - Empty dictionary + - ~mt_dict = {}~ + - ~[]~ - lists + - ~{}~ - dictionaries + - With data + #+begin_src python + extensions = {'jpg' : 'JPEG Image', + 'py' : 'Python script', + 'html' : 'Html document', + 'pdf' : 'Portable Document Format'} + #+end_src + + *Note* - ordering in dictionaries cannot be relied on +* Accessing Elements + - syntax + : extensions[key] + + : In []: print extensions['jpg'] + : Out []: JPEG Image + : In []: print extensions['zip'] +* Adding and Deleting values + - Adding a new value + : In []: extension['cpp'] = 'C++ code' + adds a new key /cpp/ with /C++ code/ as value + - Deleting values + : In []: del extensions['pdf'] + deletes the key-value pair identified by /pdf/ + - Changing value associated with a key + : In []: extension['cpp'] = 'C++ source code' + changes the value of the existing key +* Checking for container-ship of keys + : In []: 'py' in extensions + : Out []: True + Returns *True* if the /key/ is found. + : In []: 'odt' in extensions + : Out []: False + Returns *False* if the /key/ is not found. + +* Retrieve keys and values + - ~.keys()~ method + : In []: extensions.keys() + Returns a list of keys in the dictionary. + - ~.values()~ method + : In []: extensions.values() + Returns the list of values in the dictionary. +* Exercise 1 + Print the keys and values in the dictionary one by one. +* Summary + - Creating dictionaries + - empty dictionaries + - with data + - ~.keys()~ method + - ~.values()~ method + - Iterating over dictionaries +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d dictionaries/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dictionaries/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,229 @@ +% Created 2010-10-11 Mon 23:02 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Dictionaries} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Creating dictionaries + +\begin{itemize} +\item empty dictionaries +\item with data +\end{itemize} + +\item Keys and values +\item Checking for elements +\item Iterating over elements +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Overview of Dictionaries} +\label{sec-2} + +\begin{itemize} +\item A dictionary contains meaning of words + +\begin{itemize} +\item \emph{Word} is the \emph{key} here. +\item \emph{Meaning} is the \emph{value} here. +\end{itemize} + +\item A Key-Value pair data structure + +\begin{itemize} +\item Provide key-value mappings +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Creating dictionary} +\label{sec-3} + +\begin{itemize} +\item Empty dictionary + +\begin{itemize} +\item \texttt{mt\_dict = \{\}} + +\begin{itemize} +\item \texttt{[]} - lists +\item \texttt{\{\}} - dictionaries +\end{itemize} + +\end{itemize} + +\item With data +\begin{verbatim} +extensions = {'jpg' : 'JPEG Image', + 'py' : 'Python script', + 'html' : 'Html document', + 'pdf' : 'Portable Document Format'} +\end{verbatim} + + \textbf{Note} - ordering in dictionaries cannot be relied on +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Accessing Elements} +\label{sec-4} + +\begin{itemize} +\item syntax +\begin{verbatim} + extensions[key] +\end{verbatim} + +\end{itemize} + + +\begin{verbatim} + In []: print extensions['jpg'] + Out []: JPEG Image + In []: print extensions['zip'] +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Adding and Deleting values} +\label{sec-5} + +\begin{itemize} +\item Adding a new value +\begin{verbatim} + In []: extension['cpp'] = 'C++ code' +\end{verbatim} + + adds a new key \emph{cpp} with \emph{C++ code} as value +\item Deleting values +\begin{verbatim} + In []: del extensions['pdf'] +\end{verbatim} + + deletes the key-value pair identified by \emph{pdf} +\item Changing value associated with a key +\begin{verbatim} + In []: extension['cpp'] = 'C++ source code' +\end{verbatim} + + changes the value of the existing key +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Checking for container-ship of keys} +\label{sec-6} + +\begin{verbatim} + In []: 'py' in extensions + Out []: True +\end{verbatim} + + Returns \textbf{True} if the \emph{key} is found. +\begin{verbatim} + In []: 'odt' in extensions + Out []: False +\end{verbatim} + + Returns \textbf{False} if the \emph{key} is not found. +\end{frame} +\begin{frame}[fragile] +\frametitle{Retrieve keys and values} +\label{sec-7} + +\begin{itemize} +\item \texttt{.keys()} method +\begin{verbatim} + In []: extensions.keys() +\end{verbatim} + + Returns a list of keys in the dictionary. +\item \texttt{.values()} method +\begin{verbatim} + In []: extensions.values() +\end{verbatim} + + Returns the list of values in the dictionary. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 1} +\label{sec-8} + + Print the keys and values in the dictionary one by one. +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-9} + +\begin{itemize} +\item Creating dictionaries + +\begin{itemize} +\item empty dictionaries +\item with data +\end{itemize} + +\item \texttt{.keys()} method +\item \texttt{.values()} method +\item Iterating over dictionaries +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-10} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d embellishing_a_plot.rst --- a/embellishing_a_plot.rst Wed Oct 13 17:32:23 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 e675f9208b91 -r 4054b1a6392d embellishing_a_plot/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/embellishing_a_plot/questions.rst Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d embellishing_a_plot/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/embellishing_a_plot/quickref.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d embellishing_a_plot/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/embellishing_a_plot/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,388 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - + C - + D - + +.. By the end of this tutorial you will be able to + +.. * Modify the attributes of the plot -- color, line style, linewidth +.. * Add a title to the plot with embedded LaTeX. +.. * Label x and y axes. +.. * Add annotations to the plot. +.. * Set and Get the limits of axes. + + +.. 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] + +:: + clf() + plot(x, cos(x), 'r--') + +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 }}} + +:: + + annotate("root", xy=(-4,0)) + +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 e675f9208b91 -r 4054b1a6392d embellishing_a_plot/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/embellishing_a_plot/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,111 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER:\usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Embellishing a Plot +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + + Modifying the color, line style & linewidth of a plot + + Adding a title to the plot (with embedded LaTeX) + + Labelling the axes + + Annotating the plot + + Setting the limits of axes. +* Question 1 + Plot sin(x) in blue colour and with linewidth as 3 +* Solution 1 + #+begin_src python + In []: clf() + In []: plot(x, sin(x), 'b', linewidth=3) + #+end_src +* Question 2 + Plot the sine curve with green filled circles. +* Solution 2 + #+begin_src python + In []: clf() + In []: plot(x, cos(x), 'go') + #+end_src +* Question 3 + Plot the curve of x vs tan(x) in red dashed line and linewidth 3 +* Solution 3 + #+begin_src python + In []: clf() + In []: plot(x, cos(x), 'r--') + #+end_src +* Question 4 + Change the title of the figure such that the whole title is + formatted in LaTex style +* Solution 4 + #+begin_src python + In []: title("$Parabolic function -x^2+4x-5$") + #+end_src +* Question 5 + Set the x and y labels as "x" and "f(x)" in LaTex style. +* Solution 5 + #+begin_src python + In []: xlabel("$x$") + In []: yalbel("$f(x)$") + #+end_src +* Question 6 + Make an annotation called "root" at the point (-4, 0). What happens + to the first annotation? +* Solution 6 + #+begin_src python + In []: annotate("root", xy=(-4,0)) + #+end_src +* Question 7 + Set the limits of axes such that the area of interest is the + rectangle (-1, -15) and (3, 0) +* Solution 7 + #+begin_src python + In []: xlim(-1, 3) + In []: ylim(-15, 0) + #+end_src +* Summary + + 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 + +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d embellishing_a_plot/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/embellishing_a_plot/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,198 @@ +% Created 2010-10-10 Sun 17:32 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Embellishing a Plot} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Modifying the color, line style \& linewidth of a plot +\item Adding a title to the plot (with embedded \LaTeX{}) +\item Labelling the axes +\item Annotating the plot +\item Setting the limits of axes. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Plot sin(x) in blue colour and with linewidth as 3 +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +In []: clf() +In []: plot(x, sin(x), 'b', linewidth=3) +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + Plot the sine curve with green filled circles. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} + +\lstset{language=Python} +\begin{lstlisting} +In []: clf() +In []: plot(x, cos(x), 'go') +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + + Plot the curve of x vs tan(x) in red dashed line and linewidth 3 +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 3} +\label{sec-7} + +\lstset{language=Python} +\begin{lstlisting} +In []: clf() +In []: plot(x, cos(x), 'r--') +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-8} + + Change the title of the figure such that the whole title is + formatted in LaTex style +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 4} +\label{sec-9} + +\lstset{language=Python} +\begin{lstlisting} +In []: title("$Parabolic function -x^2+4x-5$") +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 5} +\label{sec-10} + + Set the x and y labels as ``x'' and ``f(x)'' in LaTex style. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 5} +\label{sec-11} + +\lstset{language=Python} +\begin{lstlisting} +In []: xlabel("$x$") +In []: yalbel("$f(x)$") +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 6} +\label{sec-12} + + Make an annotation called ``root'' at the point (-4, 0). What happens + to the first annotation? +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 6} +\label{sec-13} + +\lstset{language=Python} +\begin{lstlisting} +In []: annotate("root", xy=(-4,0)) +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 7} +\label{sec-14} + + Set the limits of axes such that the area of interest is the + rectangle (-1, -15) and (3, 0) +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 7} +\label{sec-15} + +\lstset{language=Python} +\begin{lstlisting} +In []: xlim(-1, 3) +In []: ylim(-15, 0) +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-16} + +\begin{itemize} +\item Modifying the attributes of plot by passing additional arguments +\item How to add title +\item How to incorporate \LaTeX{} style formatting +\item How to label x and y axes +\item How to add annotations +\item How to set the limits of axes +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-17} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d getting-started-files/pendulum.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-files/pendulum.txt Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,90 @@ +1.0000e-01 6.9004e-01 +1.1000e-01 6.9497e-01 +1.2000e-01 7.4252e-01 +1.3000e-01 7.5360e-01 +1.4000e-01 8.3568e-01 +1.5000e-01 8.6789e-01 +1.6000e-01 8.4182e-01 +1.7000e-01 8.5379e-01 +1.8000e-01 8.5762e-01 +1.9000e-01 8.8390e-01 +2.0000e-01 8.9985e-01 +2.1000e-01 9.8436e-01 +2.2000e-01 1.0244e+00 +2.3000e-01 1.0572e+00 +2.4000e-01 9.9077e-01 +2.5000e-01 1.0058e+00 +2.6000e-01 1.0727e+00 +2.7000e-01 1.0943e+00 +2.8000e-01 1.1432e+00 +2.9000e-01 1.1045e+00 +3.0000e-01 1.1867e+00 +3.1000e-01 1.1385e+00 +3.2000e-01 1.2245e+00 +3.3000e-01 1.2406e+00 +3.4000e-01 1.2071e+00 +3.5000e-01 1.2658e+00 +3.6000e-01 1.2995e+00 +3.7000e-01 1.3142e+00 +3.8000e-01 1.2663e+00 +3.9000e-01 1.2578e+00 +4.0000e-01 1.2991e+00 +4.1000e-01 1.3058e+00 +4.2000e-01 1.3478e+00 +4.3000e-01 1.3506e+00 +4.4000e-01 1.4044e+00 +4.5000e-01 1.3948e+00 +4.6000e-01 1.3800e+00 +4.7000e-01 1.4480e+00 +4.8000e-01 1.4168e+00 +4.9000e-01 1.4719e+00 +5.0000e-01 1.4656e+00 +5.1000e-01 1.4399e+00 +5.2000e-01 1.5174e+00 +5.3000e-01 1.4988e+00 +5.4000e-01 1.4751e+00 +5.5000e-01 1.5326e+00 +5.6000e-01 1.5297e+00 +5.7000e-01 1.5372e+00 +5.8000e-01 1.6094e+00 +5.9000e-01 1.6352e+00 +6.0000e-01 1.5843e+00 +6.1000e-01 1.6643e+00 +6.2000e-01 1.5987e+00 +6.3000e-01 1.6585e+00 +6.4000e-01 1.6317e+00 +6.5000e-01 1.7074e+00 +6.6000e-01 1.6654e+00 +6.7000e-01 1.6551e+00 +6.8000e-01 1.6964e+00 +6.9000e-01 1.7143e+00 +7.0000e-01 1.7706e+00 +7.1000e-01 1.7622e+00 +7.2000e-01 1.7260e+00 +7.3000e-01 1.8089e+00 +7.4000e-01 1.7905e+00 +7.5000e-01 1.7428e+00 +7.6000e-01 1.8381e+00 +7.7000e-01 1.8182e+00 +7.8000e-01 1.7865e+00 +7.9000e-01 1.7995e+00 +8.0000e-01 1.8296e+00 +8.1000e-01 1.8625e+00 +8.2000e-01 1.8623e+00 +8.3000e-01 1.8383e+00 +8.4000e-01 1.8593e+00 +8.5000e-01 1.8944e+00 +8.6000e-01 1.9598e+00 +8.7000e-01 1.9000e+00 +8.8000e-01 1.9244e+00 +8.9000e-01 1.9397e+00 +9.0000e-01 1.9440e+00 +9.1000e-01 1.9718e+00 +9.2000e-01 1.9383e+00 +9.3000e-01 1.9555e+00 +9.4000e-01 2.0006e+00 +9.5000e-01 1.9841e+00 +9.6000e-01 2.0066e+00 +9.7000e-01 2.0493e+00 +9.8000e-01 2.0503e+00 +9.9000e-01 2.0214e+00 diff -r e675f9208b91 -r 4054b1a6392d getting-started-files/questions.rst --- a/getting-started-files/questions.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/getting-started-files/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,17 +1,134 @@ -Objective ---------- +Objective Questions +------------------- .. A mininum of 8 questions here. -1. Question 1 -2. Question 2 -3. Question 3 +1. What function is used to open a file? + + Answer: ``open`` + +#. The ``open`` function returns a + + a. string + #. list + #. file object + #. function + + Answer: file object + +#. ``open`` function opens a file by default in write mode. T or F? + + Answer: False + +#. The ``read`` method reads a file and returns the contents + + a. string + #. list + #. file object + #. None of the above + + Answer: string + +#. Given a file with ``hello.txt``, which looks like + :: + + Hello, World! + + What is the value of content, at the end of this code block:: + + f = open('hello.txt') + pre_content = f.read() + content = f.read() + f.close() + + Answer: It is a null string. + +#. The following code block prints each line of ``hello.txt``:: + + f = open('hello.txt') + for line in f.read(): + print line + + True or False? + + Answer: False + +#. Given a file with ``hello.txt``, which looks like + :: + + Hello, World! + + What is the output of :: + + f = open('hello.txt') + + for line in f: + print line + + for line in f: + print line + + f.close() + + Answer: Hello, World! is printed once. + + .. The actual answer should talk about blank lines, but I'm + .. not sure if we should get into such detail. + + .. Should this be made a multiple-choice? + + +#. Given a file with ``hello.txt``, which looks like + :: + + Hello, World! + + What is the output of :: + + f = open('hello.txt') + + for line in f: + print line + + f.close() + + for line in f: + print line + + f.close() + + Answer: Hello, World! is printed twice. + +#. Given a file with ``hello.txt``, which looks like + :: + + Hello, World! + + What is the output of :: + + f = open('hello') + + for line in f: + print line + + f.close() + + for line in f: + print line + + f.close() + + Answer: IOError - No such file or directory: 'hello' -Programming ------------ +Larger Questions +---------------- .. A minimum of 2 questions here. -1. Programming Assignment 1 -2. Programming Assignment 2 +1. What does ``f.read(size)`` do? + +#. Print every alternate line of a file, starting at the first line. + +#. Print the file in reverse. Starting from the last line to the + first. diff -r e675f9208b91 -r 4054b1a6392d getting-started-files/quickref.tex --- a/getting-started-files/quickref.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/getting-started-files/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,8 +1,12 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} +\textbf{Getting Started -- files} + +\lstinline|f = open('filename')| returns a file object. \lstinline|f| +can be used to perform further operations on the file. -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} +\lstinline|f.read()| reads the whole file and returns the contents. + +\lstinline|f.close()| closes the file. -Plotting two lists of equal length x, y:\\ -{\ex \lstinline| plot(x, y)|} +\lstinline|for line in open('filename'):| -- iterate over the file +line-by-line. + diff -r e675f9208b91 -r 4054b1a6392d getting-started-files/script.rst --- a/getting-started-files/script.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/getting-started-files/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,10 +1,30 @@ -======== - Script -======== +.. Objectives +.. ---------- + +.. By the end of this tutorial, you will be able to +.. 1. Open and read the contents of a file. +.. #. Read files line by line. +.. #. Read all the contents of the file at once. +.. #. Close open files. + +.. Prerequisites +.. ------------- -Welcome to the tutorial on getting started with files. +.. 1. getting started with ipython +.. #. getting started with lists +.. #. getting started with for + +.. Author : Puneeth + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] -{{{ Screen shows welcome slide }}} +Script +------ + +{{{ Show the slide containing title }}} + +Hello Friends. Welcome to the tutorial on getting started with files. {{{ Show the outline for this tutorial }}} @@ -33,7 +53,8 @@ f The file object shows, the file which is open and the mode (read -or write) in which it is open. +or write) in which it is open. Notice that it is open in read only +mode, here. We shall first learn to read the whole file into a single variable. Later, we shall look at reading it line-by-line. We use @@ -54,24 +75,29 @@ pend -%%1%% Pause the video here and split the variable into a list, -``pend_list``, of the lines in the file and then resume the -video. Hint, use the tab command to see what methods the string -variable has. +Following is an exercise that you must do. + +%%1%% Split the variable into a list, ``pend_list``, of the lines in +the file. Hint, use the tab command to see what methods the string +variable has. -#[punch: should this even be put? add dependency to strings LO, -where we mention that strings have methods for manipulation. hint: -use splitlines()] +Please, pause the video here. Do the exercise and then continue. + +.. #[punch: should this even be put? add dependency to strings LO, +.. where we mention that strings have methods for manipulation. hint: +.. use splitlines()] + :: pend_list = pend.splitlines() pend_list -Now, let us learn to read the file line-by-line. But, before that -we will have to close the file, since the file has already been -read till the end. -#[punch: should we mention file-pointer?] +Now, let us learn to read the file line-by-line. But, before that we +will have to close the file, since the file has already been read till +the end. + +.. #[punch: should we mention file-pointer?] Let us close the file opened into f. :: @@ -89,8 +115,11 @@ Let us, now move on to reading files line-by-line. -%%1%% Pause the video here and re-open the file ``pendulum.txt`` -with ``f`` as the file object, and then resume the video. +Following is an exercise that you must do. + +%%2%% Re-open the file ``pendulum.txt`` with ``f`` as the file object. + +Please, pause the video here. Do the exercise and then continue. We just use the up arrow until we reach the open command and issue it again. @@ -123,8 +152,10 @@ statement. This will save us the trouble of closing the file, each time we open it. -for line in open('/home/fossee/pendulum.txt'): -line_list.append(line) +:: + + for line in open('/home/fossee/pendulum.txt'): + line_list.append(line) Let us see what ``line_list`` contains. :: @@ -143,5 +174,11 @@ a whole, using the read command or reading it line by line by iterating over the file object. -Thank you! +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India +Hope you have enjoyed and found it useful. +Thank you! + + diff -r e675f9208b91 -r 4054b1a6392d getting-started-files/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-files/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,73 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Getting started with files +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Opening and reading contents of a file + - Closing open files + - Reading all the contents of the file at once + - Reading files line by line +* Question 1 + Split the variable into a list, =pend_list=, of the lines in the + file. Hint, use the tab command to see what methods the string + variable has. +* Solution 1 + #+begin_src python + In []: pend_list = pend.splitlines() + + In []: pend_list + #+end_src +* Question 2 + Re-open the file =pendulum.txt= with =f= as the file object. +* Solution 2 + #+begin_src python + In []: f = open('/home/fossee/pendulum.txt') + #+end_src +* Summary + - Opening a file using =open= function + - Reading all the contents of the file at once using =read()= method + - Closing open files using the =close= method + - Reading files line by line by iterating using a =for= loop +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d getting-started-files/slides.tex --- a/getting-started-files/slides.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/getting-started-files/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,95 +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} +% Created 2010-10-10 Sun 17:51 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{Getting started with files} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + + \begin{frame} - \maketitle +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Opening and reading contents of a file +\item Closing open files +\item Reading all the contents of the file at once +\item Reading files line by line +\end{itemize} \end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + Split the variable into a list, \texttt{pend\_list}, of the lines in the + file. Hint, use the tab command to see what methods the string + variable has. +\end{frame} \begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} -\end{frame} +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +In []: pend_list = pend.splitlines() -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +In []: pend_list +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + Re-open the file \texttt{pendulum.txt} with \texttt{f} as the file object. +\end{frame} \begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 2} +\label{sec-5} + +\lstset{language=Python} +\begin{lstlisting} +In []: f = open('/home/fossee/pendulum.txt') +\end{lstlisting} \end{frame} - \begin{frame} - \frametitle{Thank you!} +\frametitle{Summary} +\label{sec-6} + +\begin{itemize} +\item Opening a file using \texttt{open} function +\item Reading all the contents of the file at once using \texttt{read()} method +\item Closing open files using the \texttt{close} method +\item Reading files line by line by iterating using a \texttt{for} loop +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-7} + \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r e675f9208b91 -r 4054b1a6392d getting-started-ipython/questions.rst --- a/getting-started-ipython/questions.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/getting-started-ipython/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,17 +1,186 @@ -Objective ---------- +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. ``ipython`` is a programming language similar to Python. T or F? + + Answer: False + +#. Which key combination quits ``ipython``? + + a. Ctrl + C + #. Ctrl + D + #. Alt + C + #. Alt + D + + Answer: Ctrl + D + +#. Which key combination raises a ``keyboard interrupt`` + + a. Ctrl + C + #. Ctrl + D + #. Alt + C + #. Alt + D + + Answer: Ctrl + C + +#. If you have typed the following commands:: + + 1 + 2 + 3 - 5 + 1 - 6 + 5 + 5 + 3 * 2 + + What is the result of the following actions. + + * up arrow 3 times + * backspace 4 times + + Answer: 1 + +#. If you have typed the following commands:: + + 1 + 2 + 3 - 5 + 1 - 6 + 5 + 5 + 3 * 2 + + What is the result of the following actions. + + * type ``1`` + * up arrow 2 times + + Answer: 1 + 2 + +#. If you have typed the following commands:: + + 1 + 2 + 3 - 5 + 1 - 6 + 5 + 5 + 3 * 2 + + What is the result of the following actions. + + * type ``5`` + * up arrow 2 times + + Answer: 5 + 5 + +#. If you have typed the following commands:: + + 1 + 2 + 3 - 5 + 1 - 6 + 5 + 5 + 3 * 2 + + What is the result of the following actions. + + * type ``1`` + * up arrow 1 time + * left arrow 3 times + * up arrow key + + Answer: 1 - 6 + +#. If you have typed the following commands:: -.. A mininum of 8 questions here. + 1 + 2 + 3 - 5 + 1 - 6 + 5 + 5 + 3 * 2 + + What is the result of the following actions. + + * type ``1`` + * up arrow 1 time + * left arrow 3 times + * down arrow key + + Answer: 1 - 6 + +#. If the following are only commands available in ``ipython`` + + * zebra + * zenith + * zest + + What are the commands listed by typing ``z`` and hitting the key + + Answer: zebra, zenith, zest + +#. If the following are only commands available in ``ipython`` + + * zebra + * zenith + * zest + + ``z`` is auto-completed to ``ze`` by hitting the key after typing + ``z``. T or F? + + Answer: True + + +#. If the following are only commands available in ``ipython`` + + * zebra + * zenith + * zest + + What are the commands listed by typing ``zeb`` and hitting the key + + Answer: zebra + +#. If the following are only commands available in ``ipython`` + + * zebra + * zenith + * zest + + What are the commands listed by typing ``z`` and hitting the key + + Answer: zebra, zenith, zest + +#. Which character is used at the end of a command, in ``ipython`` to display + the documentation. + + a. _ + #. ? + #. ! + #. & + + Answer: ? + +#. What happens if the size of documentation text is more than that can be + accomodated on your screen. + + a. The whole documentation is printed and it is auto scrolled to bottom + #. Only a part of documentation is shown and the remaining can be scrolled + through using up and down arrows + #. Only a part of documentation is shown and cursor returns to ``In`` prompt + + Answer: Only a part of documentation is shown and the remaining can be + scrolled through using up and down arrows + +#. Which key is used to quit the documentation that runs several pages and + return to the ``ipython`` prompt. + + a. a + #. c + #. q + #. + + Answer: q + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) 1. Question 1 2. Question 2 -3. Question 3 - - -Programming ------------ - -.. A minimum of 2 questions here. - -1. Programming Assignment 1 -2. Programming Assignment 2 diff -r e675f9208b91 -r 4054b1a6392d getting-started-ipython/quickref.tex --- a/getting-started-ipython/quickref.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/getting-started-ipython/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,8 +1,14 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} +\textbf{Getting started -- \texttt{ipython}} + +To start \lstinline|ipython| with \lstinline|pylab|:\\ +\lstinline| $ ipython -pylab| %$ + +To exit: \lstinline|^D| (Ctrl-D) -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} +To interrupt: \lstinline|^C| (Ctrl-C) + +Tab completes partial commands -Plotting two lists of equal length x, y:\\ -{\ex \lstinline| plot(x, y)|} +\texttt{?} to look up documentation. + +Arrow keys to navigate the history. diff -r e675f9208b91 -r 4054b1a6392d getting-started-ipython/script.rst --- a/getting-started-ipython/script.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/getting-started-ipython/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,14 +1,19 @@ .. Objectives .. ---------- -.. Clearly state the objectives of the LO (along with RBT level) +.. At the end of this tutorial, you will be able to + +.. 1. invoke the ``ipython`` interpreter. +.. #. quit the ``ipython`` interpreter. +.. #. navigate in the history of ``ipython``. +.. #. use tab-completion. +.. #. look-up documentation of functions. +.. #. interrupt incomplete or incorrect commands. .. Prerequisites .. ------------- -.. 1. Name of LO-1 -.. 2. Name of LO-2 -.. 3. Name of LO-3 +.. should have ``ipython`` and ``pylab`` installed. .. Author : Puneeth Internal Reviewer : @@ -24,14 +29,14 @@ Hello Friends and Welcome to the tutorial on getting started with ``ipython``. -{{{ Show slide with outline of the session. }}} +{{{ Show slide with outline }}} This tutorial will cover the basic usage of the ``ipython`` interpreter. The following topics would be covered. IPython is an enhanced Python interpreter that provides features like -tabcompletion, easier access to help and many other functionalities -which are not available in the vannila Python interpreter. +tabcompletion, easier access to help and lot of other functionality +which are not available in the vanilla Python interpreter. First let us see how to invoke the ``ipython`` interpreter. @@ -98,8 +103,12 @@ tab. IPython does not complete the command since there are many possibilities. It just lists out all the possible completions. -%% %% Pause the video here and type ``ab`` and hit tab to see what -happens. Next, jut type ``a`` and hit tab to see what happens. +Following is an exercise that you must do. + +%%1%% Type ``ab`` and hit tab to see what happens. Next, just type +``a`` and hit tab to see what happens. + +Please, pause the video here. Do the exercise and then continue. ``ab`` tab completes to ``abs`` and ``a`` gives us a list of all the commands starting with a. @@ -125,11 +134,11 @@ Does it work for decimals (or floats)? Let's try typing abs(-10.5) and we do get back 10.5. -Following is an (are) exercise(s) that you must do. +Following is an exercise that you must do. -%%1%% Look-up the documentation of ``round`` and see how to use it. +%%2%% Look-up the documentation of ``round`` and see how to use it. -Please, pause the video here. Do the exercises and then continue. +Please, pause the video here. Do the exercise and then continue. :: @@ -142,17 +151,20 @@ The function ``round``, rounds a number to a given precision. -%% %% Pause the video here and check the output of -round(2.48) -round(2.48, 1) -round(2.48, 2) -and then resume the video. +Following are exercises that you must do. + +%%3%% Check the output of:: -:: + round(2.48) + round(2.48, 1) + round(2.48, 2) + round(2.484) round(2.484, 1) round(2.484, 2) +Please, pause the video here. Do the exercises and then continue. + We get 2.0, 2.5 and 2.48, which are what we expect. Let's now see how to correct typing errors that we make when typing at @@ -174,7 +186,7 @@ Following is an exercise that you must do. -%%2%% Try typing round(2.484, and hit enter. and then cancel the +%%4%% Try typing round(2.484, and hit enter. and then cancel the command using Ctrl-C. Then, type the command, round(2.484, 2) and resume the video. @@ -190,9 +202,15 @@ This brings us to the end of the tutorial on getting started with ``ipython``. -In this tutorial we have learnt +In this tutorial we have learnt, how to {{{ show the outline/summary slide. }}} + 1. invoke the ``ipython`` interpreter. + #. quit the ``ipython`` interpreter. + #. navigate in the history of ``ipython``. + #. use tab-completion. + #. look-up documentation of functions. + #. interrupt incomplete or incorrect commands. {{{ Show the "sponsored by FOSSEE" slide }}} diff -r e675f9208b91 -r 4054b1a6392d getting-started-ipython/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-ipython/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,61 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER:\usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Getting Started -- ~ipython~ +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + + invoke the ~ipython~ interpreter + + quit the ~ipython~ interpreter + + navigate in the history of ~ipython~ + + use tab-completion + + look-up documentation of functions + + interrupt incomplete or incorrect commands +* Summary + + invoking and quitting the ~ipython~ interpreter + + navigating the history + + using tab-completion to work faster + + looking-up documentation using ~?~ + + sending keyboard interrupts using ~Ctrl-C~ + +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d getting-started-ipython/slides.tex --- a/getting-started-ipython/slides.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/getting-started-ipython/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,95 +1,74 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{infolines} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} +% Created 2010-10-10 Sun 17:34 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{Getting Started -- \texttt{ipython}} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + \begin{frame} - \maketitle -\end{frame} - -\begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} -\end{frame} +\frametitle{Outline} +\label{sec-1} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\begin{itemize} +\item invoke the \texttt{ipython} interpreter +\item quit the \texttt{ipython} interpreter +\item navigate in the history of \texttt{ipython} +\item use tab-completion +\item look-up documentation of functions +\item interrupt incomplete or incorrect commands +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-2} -\begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} +\begin{itemize} +\item invoking and quitting the \texttt{ipython} interpreter +\item navigating the history +\item using tab-completion to work faster +\item looking-up documentation using \texttt{?} +\item sending keyboard interrupts using \texttt{Ctrl-C} +\end{itemize} \end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-3} -\begin{frame} - \frametitle{Thank you!} \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r e675f9208b91 -r 4054b1a6392d getting-started-sagenotebook.rst --- a/getting-started-sagenotebook.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,295 +0,0 @@ -Hello friends. Welcome to this spoken tutorial on Getting started with -sage and sage notebook. - -{{{ Show the slide containing the title }}} - -{{{ Show the slide containing the outline }}} - -In this tutorial, we will learn what Sage is, what is Sage notebook, -how to start and use the sage notebook. In the notebook we will be -specifically learning how to execute our code, how to write -annotations and other content, typesetting the content and how to use -the offline help available. - -{{{ Show the slide on what is Sage }}} - -To start with, What is Sage? Sage is a free, open-source mathematical -software. Sage can do a lot of math stuff for you including but not -limited to algebra, calculus, geometry, cryptography, graph theory -among other things. It can also be used as aid in teaching and -research in any of the areas that Sage supports. So let us start Sage -now - -{{{ Shift to terminal }}} - -We are assuming that you have Sage installed on your computer now. If -not please visit the page -http://sagemath.org/doc/tutorial/introduction.html#installation for -the tutorial on how to install Sage. Let us move on now. - -On the terminal type:: - - sage - -This should start a new Sage shell with the prompt sage: which looks -like this - -{{{ Show what is displayed on the terminal }}} - -So now we can type all the commands that Sage supports here. But Sage -comes bundled with a much much much more elegant tool called Sage -Notebook? What is Sage Notebook? Sage Notebook provides a web based -user interface to use Sage. So once we have a Sage notebook server up -and running all we want is a browser to access the Sage -functionality. For example there is an official instance of Sage -Notebook server running at http://sagenb.org You can visit that page, -create an account there and start using Sage! So all you need is just -a browser, a modern browser - -{{{ Intentional *cough* *cough* }}} - -to use Sage and nothing else! The Sage notebook also provides a -convenient way of sharing and publishing our work which is very handy -when we use Sage for research or for teaching. - -However we can also run our own instances of Sage notebook servers on -all the computers we have a local installation of Sage. To start the -notebook server just type:: - - notebook() - -on the Sage prompt. This will start the Sage Notebook server. If we -are starting the notebook server for the first time, we are prompted -to enter the password for the admin. Type the password and make a note -of it. After this Sage automatically starts a browser page for you -with the notebook opened. - -If it doesn't automatically start a browser page check if the Notebook -server started and there were no problems. If so open your browser and -in the address bar type the URL shown in the instructions upon running -the notebook command on the sage prompt. - -{{{ The notebook() command gives an instruction telling -Open your web browser to http://localhost:8000. Point towards it }}} - -In our case it is http://localhost:{{{ Tell whatever is shown }}} - -{{{ Show the browser with Sage notebook }}} - -If you are not logged in yet, it shows the Notebook home page and -textboxes to type the username and the password. You can use the -username 'admin' and the password you gave while starting the notebook -server for the first time. There are also links to recover forgotten -password and to create new accounts. - -{{{ If you are logged in tell that you are logged in, log out and show -what is said above for the login page }}} - -Once we are logged in with the admin account we can see the notebook -admin page. A notebook can contain a collection of Sage Notebook -worksheets. Worksheets are basically the working area. This is where -we enter all the Sage commands on the notebook. - -The admin page lists all the worksheets created. On the topmost part -of this page we have the links to various pages. - -{{{ Whenever you talk on an individual link point your mouse towards -the link. For each of the link go to the page and explain as below }}} - -The home link takes us to the admin home page. The published link -takes us to the page which lists all the published worksheets. The log -link has the complete log of all the actions we did on the -notebook. We have the settings link where can configure our notebook, -the notebook server, we can create and mangage accounts. We have a -link to help upon clicking opens a new window with the complete help -of Sage. The entire documentation of Sage is supplied with Sage for -offline reference and this help link is the way to get into it. Then -we can report bugs about Sage by clicking on Report a Problem link and -there is a link to sign out of the notebook. - -We can create a new worksheet by clicking New Worksheet link - -{{{ Click on the link }}} - -Sage prompts you for a name for the worksheet. Let us name the -worksheet as nbtutorial. Now we have our first worksheet which is -empty. - -A worksheet will contain a collection of cells. Every Sage command -must be entered in this cell. Cell is equivalent to the prompt on -console. When we create a new worksheet, to start with we will have -one empty cell. Let us try out some math here:: - - 2 + 2 - 57.1 ^ 100 - -The cap operator is used for exponentiation. If you observed carefully -we typed two commands but the output of only last command was -displayed. By default each cell displays the result of only the last -operation. We have to use print statement to display all the results -we want to be displayed. - -{{{ Demonstrate creating a new cell }}} - -Now to perform more operations we want more cells. So how do we create -a new cell? It is very simple. As we hover our mouse above or below -the existing cells we see a blue line, by clicking on this new line we -can create a new cell. - -We have a cell, we have typed some commands in it, but how do we -evaluate that cell? Pressing Shift along with Enter evaluates the -cell. Alternatively we can also click on the evaluate link to evaluate -the cell - -{{{ Evaluate the cell and demonstrate for both methods separately -}}}:: - - matrix([[1,2], [3,4]])^(-1) - -After we create many cells, we may want to move between the cells. To -move between the cells use Up and Down arrow keys. Also clicking on -the cell will let you edit that particular cell. - -{{{ Move between two cells created }}} - -To delete a cell, clear the contents of the cell and hit backspace - -{{{ Clear and demonstrate deleting the cell }}}:: - - Makes no sense - -If you want to add annotations in the worksheet itself on the blue -line that appears on hovering the mouse around the cell, Hold Shift -and click on the line. This creates a What You See Is What You Get -cell. - -{{{ Create a HTML editable cell }}} - -We can make our text here rich text. We can make it bold, Italics, we -can create bulleted and enumerated lists in this area:: - - This text contains both the **bold** text and also *italicised* - text. - It also contains bulleted list: - * Item 1 - * Item 2 - It also contains enumerate list: - 1. Item 1 - 2. Item 2 - -In the same cell we can display typeset math using the LaTeX like -syntax:: - - $\int_0^\infty e^{-x} \, dx$ - -We enclose the math to be typeset within $ and $ or $$ and $$ as in -LaTeX. - -We can also obtain help for a particular Sage command or function -within the worksheet itself by using a question mark following the -command:: - - sin? - -Evaluating this cell gives me the entire help for the sin function -inline on the worksheet itself. Similarly we can also look at the -source code of each command or function using double question mark:: - - matrix?? - -Sage notebook also provides the feature for autocompletion. To -autocomplete a command type first few unique characters and hit tab -key:: - - sudo - -To see all the commands starting with a specific name type those -characters and hit tab:: - - plo - -To list all the methods that are available for a certain variable or -a datatype we can use the variable name followed by the dot to access -the methods available on it and then hit tab:: - - s = 'Hello' - s.rep - -The output produced by each cell can be one of the three states. It -can be either the full output, or truncated output or hidden output. -The output area will display the error if the Sage code we wrote in -the cell did not successfully execute:: - - a, b = 10 - -{{{ Show the three states }}} - -The default output we obtained now is a truncated output. Clicking at -the left of the output area when the mouse pointer turns to hand gives -us the full output, clicking again makes the output hidden and it -cycles. - -Lastly, Sage supports a variety of languages and each cell on the -worksheet can contain code written in a specific language. It is -possible to instruct Sage to interpret the code in the language we -have written. This can be done by putting percentage sign(%) followed -by the name of the language. For example, to interpret the cell as -Python code we put:: - - %python - -as the first line in the cell. Similarly we have: %sh for shell -scripting, %fortran for Fortran, %gap for GAP and so on. Let us see -how this works. Say I have an integer. The type of the integer in -default Sage mode is -{{{ Read the output }}}:: - - a = 1 - type(a) - - Output: - -We see that Integers are Sage Integers. Now let us put %python as the -first line of the cell and execute the same code snippet:: - - %python - a = 1 - type(a) - - Output: - -Now we see that the integer is a Python integer. Why? Because now we -instructed Sage to interpret that cell as Python code. - -This brings us to the end of the tutorial on using Sage. We learnt -quite a lot about using the Notebook User Interface of Sage. We are -now confident that we can comfortably use the notebook to learn more -about Sage in the following tutorials. Let us summarize what we -learnt. In this session we learnt - - * What is Sage - * How to start Sage shell - * What is Sage notebook - * How to start the Sage notebook - * How to create accounts and start using the notebook - * How to create new worksheets - * The menus available on the notebook - * About cells in the worksheet - * Methods to evaluate the cell, create new cells, delete the cells - and navigate around the cells - * To make annotations in the worksheet - * Tab completions - * And embedding code of other scripting languages in the cells - -{{{ Show the "sponsored by FOSSEE" slide }}} - -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thankyou - -.. Author : Madhu - Internal Reviewer 1 : [potential reviewer: Anoop] - Internal Reviewer 2 : [potential reviewer: Puneeth] - External Reviewer : - diff -r e675f9208b91 -r 4054b1a6392d getting-started-sagenotebook/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-sagenotebook/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,28 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Question 1 + + Answer: Answer 1 + + OR + + Answer:: + + answer code line 1 + answer code line 2 + answer code line 3 + +2. Question 2 +3. Question 3 + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Question 1 +2. Question 2 diff -r e675f9208b91 -r 4054b1a6392d getting-started-sagenotebook/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-sagenotebook/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,8 @@ +Creating a linear array:\\ +{\ex \lstinline| x = linspace(0, 2*pi, 50)|} + +Plotting two variables:\\ +{\ex \lstinline| plot(x, sin(x))|} + +Plotting two lists of equal length x, y:\\ +{\ex \lstinline| plot(x, y)|} diff -r e675f9208b91 -r 4054b1a6392d getting-started-sagenotebook/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-sagenotebook/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,323 @@ +.. Objectives +.. ---------- + +.. Clearly state the objectives of the LO (along with RBT level) + +.. By the end of this tutorial, you should -- + +.. #. Know what Sage and Sage notebook are. +.. #. Be able to start a Sage shell or notebook +.. #. Be able to start using the notebook +.. #. Be able to create new worksheets +.. #. Know about the menu options available +.. #. Know about the cells in the worksheet +.. #. Be able to evaluate cells, create and delete cells, navigate them. +.. #. Be able to make annotations in the worksheet +.. #. Be able to use tab completion. +.. #. Be able to use code from other languages in the cells. + +.. Prerequisites +.. ------------- + +.. None. + +.. Author : Madhu + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + + +Script +------ + +Hello friends. Welcome to this spoken tutorial on Getting started with +sage and sage notebook. + +{{{ Show the slide containing the title }}} + +{{{ Show the slide containing the outline }}} + +In this tutorial, we will learn what Sage is, what is Sage notebook, +how to start and use the sage notebook. In the notebook we will be +specifically learning how to execute our code, how to write +annotations and other content, typesetting the content and how to use +the offline help available. + +{{{ Show the slide on what is Sage }}} + +To start with, What is Sage? Sage is a free, open-source mathematical +software. Sage can do a lot of math stuff for you including but not +limited to algebra, calculus, geometry, cryptography, graph theory +among other things. It can also be used as aid in teaching and +research in any of the areas that Sage supports. So let us start Sage +now + +{{{ Shift to terminal }}} + +We are assuming that you have Sage installed on your computer now. If +not please visit the page +http://sagemath.org/doc/tutorial/introduction.html#installation for +the tutorial on how to install Sage. Let us move on now. + +On the terminal type:: + + sage + +This should start a new Sage shell with the prompt sage: which looks +like this + +{{{ Show what is displayed on the terminal }}} + +So now we can type all the commands that Sage supports here. But Sage +comes bundled with a much much much more elegant tool called Sage +Notebook? What is Sage Notebook? Sage Notebook provides a web based +user interface to use Sage. So once we have a Sage notebook server up +and running all we want is a browser to access the Sage +functionality. For example there is an official instance of Sage +Notebook server running at http://sagenb.org You can visit that page, +create an account there and start using Sage! So all you need is just +a browser, a modern browser + +{{{ Intentional *cough* *cough* }}} + +to use Sage and nothing else! The Sage notebook also provides a +convenient way of sharing and publishing our work which is very handy +when we use Sage for research or for teaching. + +However we can also run our own instances of Sage notebook servers on +all the computers we have a local installation of Sage. To start the +notebook server just type:: + + notebook() + +on the Sage prompt. This will start the Sage Notebook server. If we +are starting the notebook server for the first time, we are prompted +to enter the password for the admin. Type the password and make a note +of it. After this Sage automatically starts a browser page for you +with the notebook opened. + +If it doesn't automatically start a browser page check if the Notebook +server started and there were no problems. If so open your browser and +in the address bar type the URL shown in the instructions upon running +the notebook command on the sage prompt. + +{{{ The notebook() command gives an instruction telling +Open your web browser to http://localhost:8000. Point towards it }}} + +In our case it is http://localhost:{{{ Tell whatever is shown }}} + +{{{ Show the browser with Sage notebook }}} + +If you are not logged in yet, it shows the Notebook home page and +textboxes to type the username and the password. You can use the +username 'admin' and the password you gave while starting the notebook +server for the first time. There are also links to recover forgotten +password and to create new accounts. + +{{{ If you are logged in tell that you are logged in, log out and show +what is said above for the login page }}} + +Once we are logged in with the admin account we can see the notebook +admin page. A notebook can contain a collection of Sage Notebook +worksheets. Worksheets are basically the working area. This is where +we enter all the Sage commands on the notebook. + +The admin page lists all the worksheets created. On the topmost part +of this page we have the links to various pages. + +{{{ Whenever you talk on an individual link point your mouse towards +the link. For each of the link go to the page and explain as below }}} + +The home link takes us to the admin home page. The published link +takes us to the page which lists all the published worksheets. The log +link has the complete log of all the actions we did on the +notebook. We have the settings link where can configure our notebook, +the notebook server, we can create and mangage accounts. We have a +link to help upon clicking opens a new window with the complete help +of Sage. The entire documentation of Sage is supplied with Sage for +offline reference and this help link is the way to get into it. Then +we can report bugs about Sage by clicking on Report a Problem link and +there is a link to sign out of the notebook. + +We can create a new worksheet by clicking New Worksheet link + +{{{ Click on the link }}} + +Sage prompts you for a name for the worksheet. Let us name the +worksheet as nbtutorial. Now we have our first worksheet which is +empty. + +A worksheet will contain a collection of cells. Every Sage command +must be entered in this cell. Cell is equivalent to the prompt on +console. When we create a new worksheet, to start with we will have +one empty cell. Let us try out some math here:: + + 2 + 2 + 57.1 ^ 100 + +The cap operator is used for exponentiation. If you observed carefully +we typed two commands but the output of only last command was +displayed. By default each cell displays the result of only the last +operation. We have to use print statement to display all the results +we want to be displayed. + +{{{ Demonstrate creating a new cell }}} + +Now to perform more operations we want more cells. So how do we create +a new cell? It is very simple. As we hover our mouse above or below +the existing cells we see a blue line, by clicking on this new line we +can create a new cell. + +We have a cell, we have typed some commands in it, but how do we +evaluate that cell? Pressing Shift along with Enter evaluates the +cell. Alternatively we can also click on the evaluate link to evaluate +the cell + +{{{ Evaluate the cell and demonstrate for both methods separately +}}}:: + + matrix([[1,2], [3,4]])^(-1) + +After we create many cells, we may want to move between the cells. To +move between the cells use Up and Down arrow keys. Also clicking on +the cell will let you edit that particular cell. + +{{{ Move between two cells created }}} + +To delete a cell, clear the contents of the cell and hit backspace + +{{{ Clear and demonstrate deleting the cell }}}:: + + Makes no sense + +If you want to add annotations in the worksheet itself on the blue +line that appears on hovering the mouse around the cell, Hold Shift +and click on the line. This creates a What You See Is What You Get +cell. + +{{{ Create a HTML editable cell }}} + +We can make our text here rich text. We can make it bold, Italics, we +can create bulleted and enumerated lists in this area:: + + This text contains both the **bold** text and also *italicised* + text. + It also contains bulleted list: + * Item 1 + * Item 2 + It also contains enumerate list: + 1. Item 1 + 2. Item 2 + +In the same cell we can display typeset math using the LaTeX like +syntax:: + + $\int_0^\infty e^{-x} \, dx$ + +We enclose the math to be typeset within $ and $ or $$ and $$ as in +LaTeX. + +We can also obtain help for a particular Sage command or function +within the worksheet itself by using a question mark following the +command:: + + sin? + +Evaluating this cell gives me the entire help for the sin function +inline on the worksheet itself. Similarly we can also look at the +source code of each command or function using double question mark:: + + matrix?? + +Sage notebook also provides the feature for autocompletion. To +autocomplete a command type first few unique characters and hit tab +key:: + + sudo + +To see all the commands starting with a specific name type those +characters and hit tab:: + + plo + +To list all the methods that are available for a certain variable or +a datatype we can use the variable name followed by the dot to access +the methods available on it and then hit tab:: + + s = 'Hello' + s.rep + +The output produced by each cell can be one of the three states. It +can be either the full output, or truncated output or hidden output. +The output area will display the error if the Sage code we wrote in +the cell did not successfully execute:: + + a, b = 10 + +{{{ Show the three states }}} + +The default output we obtained now is a truncated output. Clicking at +the left of the output area when the mouse pointer turns to hand gives +us the full output, clicking again makes the output hidden and it +cycles. + +Lastly, Sage supports a variety of languages and each cell on the +worksheet can contain code written in a specific language. It is +possible to instruct Sage to interpret the code in the language we +have written. This can be done by putting percentage sign(%) followed +by the name of the language. For example, to interpret the cell as +Python code we put:: + + %python + +as the first line in the cell. Similarly we have: %sh for shell +scripting, %fortran for Fortran, %gap for GAP and so on. Let us see +how this works. Say I have an integer. The type of the integer in +default Sage mode is +{{{ Read the output }}}:: + + a = 1 + type(a) + + Output: + +We see that Integers are Sage Integers. Now let us put %python as the +first line of the cell and execute the same code snippet:: + + %python + a = 1 + type(a) + + Output: + +Now we see that the integer is a Python integer. Why? Because now we +instructed Sage to interpret that cell as Python code. + +This brings us to the end of the tutorial on using Sage. We learnt +quite a lot about using the Notebook User Interface of Sage. We are +now confident that we can comfortably use the notebook to learn more +about Sage in the following tutorials. Let us summarize what we +learnt. In this session we learnt + + * What is Sage + * How to start Sage shell + * What is Sage notebook + * How to start the Sage notebook + * How to create accounts and start using the notebook + * How to create new worksheets + * The menus available on the notebook + * About cells in the worksheet + * Methods to evaluate the cell, create new cells, delete the cells + and navigate around the cells + * To make annotations in the worksheet + * Tab completions + * And embedding code of other scripting languages in the cells + +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you! + + diff -r e675f9208b91 -r 4054b1a6392d getting-started-sagenotebook/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-sagenotebook/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,123 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Accessing parts of arrays +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Manipulating one and multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slicing and striding on arrays to access chunks + - Read images into arrays and manipulations +* Sample Arrays + #+begin_src python + In []: A = array([12, 23, 34, 45, 56]) + + In []: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) + + #+end_src +* Question 1 + Change the last column of ~C~ to zeroes. +* Solution 1 + #+begin_src python + In []: C[:, -1] = 0 + #+end_src +* Question 2 + Change ~A~ to ~[11, 12, 13, 14, 15]~. +* Solution 2 + #+begin_src python + In []: A[:] = [11, 12, 13, 14, 15] + #+end_src +* squares.png + #+begin_latex + \begin{center} + \includegraphics[scale=0.6]{squares} + \end{center} + #+end_latex +* Question 3 + - obtain ~[22, 23]~ from ~C~. + - obtain ~[11, 21, 31, 41]~ from ~C~. + - obtain ~[21, 31, 41, 0]~. +* Solution 3 + #+begin_src python + In []: C[1, 1:3] + In []: C[0:4, 0] + In []: C[1:5, 0] + #+end_src +* Question 4 + Obtain ~[[23, 24], [33, -34]]~ from ~C~ +* Solution 4 + #+begin_src python + In []: C[1:3, 2:4] + #+end_src +* Question 5 + Obtain the square in the center of the image +* Solution 5 + #+begin_src python + In []: imshow(I[75:225, 75:225]) + #+end_src +* Question 6 + Obtain the following + #+begin_src python + [[12, 0], [42, 0]] + [[12, 13, 14], [0, 0, 0]] + #+end_src + +* Solution 6 + #+begin_src python + In []: C[::3, 1::3] + In []: C[::4, 1:4] + #+end_src +* Summary + You should now be able to -- + - Manipulate 1D \& Multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slice and stride on arrays + - Read images into arrays and manipulate them. +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d getting-started-sagenotebook/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-sagenotebook/slides.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d getting-started-strings.rst --- a/getting-started-strings.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,125 +0,0 @@ -Hello friends. Welcome to this spoken tutorial on Getting started with -strings. - -{{{ Show the slide containing the title }}} - -{{{ Show the slide containing the outline }}} - -In this tutorial, we will learn what do we actually mean by strings in -python, how python supports the use of strings. We will also learn -some of the operations that can be performed on strings. - -{{{ Shift to terminal and start ipython }}} - -To begin with let us start ipython, by typing:: - - ipython - -on the terminal - -So what are strings? In Python anything within either single quotes -or double quotes or triple single quotes or triple double quotes are -strings. This is true whatsoever, even if there is only one character -within the quotes - -{{{ Type in ipython the following and read them as you type }}}:: - - 'This is a string' - "This is a string too' - '''This is a string as well''' - """This is also a string""" - 'p' - -Having more than one control character to define strings come as very -handy when one of the control characters itself is part of the -string. For example:: - - "Python's string manipulation functions are very useful" - -In this case we use single quote for apostrophe. If we had only single -quote to define strings we should have a clumsy way of escaping the -single quote character to make it part of the string. Hence this is a -very handy feature. - -The triple quoted strings let us define multi-lines strings without -using any escaping. Everything within the triple quotes is a single -string no matter how many lines it extends:: - - """Having more than one control character to define - strings come as very handy when one of the control - characters itself is part of the string.""" - -We can assign this string to any variable:: - - a = 'Hello, World!' - -Now 'a' is a string variable. String is a collection of characters. In -addition string is an immutable collection. So all the operations that -are applicable to any other immutable collection in Python works on -string as well. So we can add two strings:: - - a = 'Hello' - b = 'World' - c = a + ', ' + b + '!' - -We can add string variables as well as the strings themselves all in -the same statement. The addition operation performs the concatenation -of two strings. - -Similarly we can multiply a string with an integer:: - - a = 'Hello' - a * 5 - -gives another string in which the original string 'Hello' is repeated -5 times. - -Since strings are collections we can access individual items in the -string using the subscripts:: - - a[0] - -gives us the first character in the string. The indexing starts from 0 -for the first character up to n-1 for the last character. We can -access the strings from the end using negative indices:: - - a[-2] - -gives us second element from the end of the string - -Let us attempt to change one of the characters in a string:: - - a = 'hello' - a[0] = 'H' - -As said earlier, strings are immutable. We cannot manipulate the -string. Although there are some methods which let us to manipulate the -strings. We will look at them in the advanced session on strings. In -addition to the methods that let us manipulate the strings we have -methods like split which lets us break the string on the specified -separator, the join method which lets us combine the list of strings -into a single string based on the specified separator. - -{{{ Show summary slide }}} - -This brings us to the end of another session. In this tutorial session -we learnt - - * How to define strings - * Different types of defining a string - * String concatenation and repeatition - * Accessing individual elements of the string - * Immutability of strings - -{{{ Show the "sponsored by FOSSEE" slide }}} - -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thankyou - -.. Author : Madhu - Internal Reviewer 1 : [potential reviewer: Nishanth] - Internal Reviewer 2 : [potential reviewer: Amit] - External Reviewer : - diff -r e675f9208b91 -r 4054b1a6392d getting-started-strings/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-strings/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,80 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. List the type of quotes that can be used to define strings. + + Answer: 'single quotes', "double quotes", + '''triple single quotes''' + """triple double quotes""" + +#. Given the strings ``s`` and ``S``, ``s='Hello World'`` and + ``S="Hello World``. s and S are different strings. True or False? + +#. What is the output of:: + + s = 'It's all here' + + Answer: ``SyntaxError`` + +#. Write code to assign s, the string ``' is called the apostrophe`` + + Answer: ``s = "`is called the apostrophe"`` + +#. Given strings s and t, ``s = "Hello"`` and ``t = "World"``. What is + the output of s + t? + + Answer: HelloWorld + +#. Given strings s and t, ``s = "Hello"`` and ``t = "World"`` and an + integer r, ``r = 2``. What is the output of s * r + s * t? + + Answer: HelloHelloWorldWorld + +#. Given strings s and t, ``s = "Hello"`` and ``t = "World"`` and an + integer r, ``r = 2``. What is the output of s * 'r' ? + + Answer: TypeError - can't multiply a sequence by non-int + +#. Given the string ``s = "Hello"``, we wish to change it to + ``hello``. what is the result of:: + + s[0] = 'h' + + Answer: TypeError - 'str' object does not support item assignment. + +#. Given the string ``s = "Hello"``, we wish to change it to + ``hello``. what is the result of:: + + s = "hello" + + Answer: s is changed to "hello" + +#. Which type of string can be written in multiple lines, with line + breaks. (Note: more than one answer may be correct.) + + #. triple double quoted strings + #. single quoted strings + #. double quoted strings + #. triple single quoted strings + + Answer: triple double quoted strings and triple single quoted strings + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Given the string s, ``s = F.R.I.E.N.D.S``, obtain the string + "FRIENDS". + + Answer:: + + s = s[0] + s[2] + s[4] + s[6] + s[8] + s[10] + s[12] + +2. Assign the string ``Today's Quote: "Don't believe in any quote, + including this."`` to the variable ``quote``. + + Answer: + quote = """Today's Quote: "Don't believe in any quote, including this.""" diff -r e675f9208b91 -r 4054b1a6392d getting-started-strings/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-strings/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,8 @@ +Creating a linear array:\\ +{\ex \lstinline| x = linspace(0, 2*pi, 50)|} + +Plotting two variables:\\ +{\ex \lstinline| plot(x, sin(x))|} + +Plotting two lists of equal length x, y:\\ +{\ex \lstinline| plot(x, y)|} diff -r e675f9208b91 -r 4054b1a6392d getting-started-strings/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-strings/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,145 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you should know -- + +.. 1. How to define strings +.. #. Different ways of defining a string +.. #. How to concatenate strings +.. #. How to print a string repeatedly +.. #. Accessing individual elements of the string +.. #. Immutability of strings + +.. Prerequisites +.. ------------- + +.. 1. getting started with ipython + +.. Author : Madhu + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +{{{ Show the slide containing the title }}} + +Hello friends. Welcome to this spoken tutorial on Getting started with +strings. + +{{{ Show the slide containing the outline }}} + +In this tutorial, we will learn what do we actually mean by strings in +python, how python supports the use of strings. We will also learn +some of the operations that can be performed on strings. + +{{{ Shift to terminal and start ipython }}} + +To begin with let us start ipython, by typing:: + + ipython + +on the terminal + +So what are strings? In Python anything within either single quotes +or double quotes or triple single quotes or triple double quotes are +strings. This is true whatsoever, even if there is only one character +within the quotes + +{{{ Type in ipython the following and read them as you type }}}:: + + 'This is a string' + "This is a string too' + '''This is a string as well''' + """This is also a string""" + 'p' + +Having more than one control character to define strings come as very +handy when one of the control characters itself is part of the +string. For example:: + + "Python's string manipulation functions are very useful" + +In this case we use single quote for apostrophe. If we had only single +quote to define strings we should have a clumsy way of escaping the +single quote character to make it part of the string. Hence this is a +very handy feature. + +The triple quoted strings let us define multi-lines strings without +using any escaping. Everything within the triple quotes is a single +string no matter how many lines it extends:: + + """Having more than one control character to define + strings come as very handy when one of the control + characters itself is part of the string.""" + +We can assign this string to any variable:: + + a = 'Hello, World!' + +Now 'a' is a string variable. String is a collection of characters. In +addition string is an immutable collection. So all the operations that +are applicable to any other immutable collection in Python works on +string as well. So we can add two strings:: + + a = 'Hello' + b = 'World' + c = a + ', ' + b + '!' + +We can add string variables as well as the strings themselves all in +the same statement. The addition operation performs the concatenation +of two strings. + +Similarly we can multiply a string with an integer:: + + a = 'Hello' + a * 5 + +gives another string in which the original string 'Hello' is repeated +5 times. + +Since strings are collections we can access individual items in the +string using the subscripts:: + + a[0] + +gives us the first character in the string. The indexing starts from 0 +for the first character up to n-1 for the last character. We can +access the strings from the end using negative indices:: + + a[-2] + +gives us second element from the end of the string + +Let us attempt to change one of the characters in a string:: + + a = 'hello' + a[0] = 'H' + +As said earlier, strings are immutable. We cannot manipulate the +string. Although there are some methods which let us to manipulate the +strings. We will look at them in the advanced session on strings. In +addition to the methods that let us manipulate the strings we have +methods like split which lets us break the string on the specified +separator, the join method which lets us combine the list of strings +into a single string based on the specified separator. + +{{{ Show summary slide }}} + +This brings us to the end of another session. In this tutorial session +we learnt + + * How to define strings + * Different ways of defining a string + * String concatenation and repeatition + * Accessing individual elements of the string + * Immutability of strings + +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you! + diff -r e675f9208b91 -r 4054b1a6392d getting-started-strings/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-strings/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,123 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Accessing parts of arrays +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Manipulating one and multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slicing and striding on arrays to access chunks + - Read images into arrays and manipulations +* Sample Arrays + #+begin_src python + In []: A = array([12, 23, 34, 45, 56]) + + In []: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) + + #+end_src +* Question 1 + Change the last column of ~C~ to zeroes. +* Solution 1 + #+begin_src python + In []: C[:, -1] = 0 + #+end_src +* Question 2 + Change ~A~ to ~[11, 12, 13, 14, 15]~. +* Solution 2 + #+begin_src python + In []: A[:] = [11, 12, 13, 14, 15] + #+end_src +* squares.png + #+begin_latex + \begin{center} + \includegraphics[scale=0.6]{squares} + \end{center} + #+end_latex +* Question 3 + - obtain ~[22, 23]~ from ~C~. + - obtain ~[11, 21, 31, 41]~ from ~C~. + - obtain ~[21, 31, 41, 0]~. +* Solution 3 + #+begin_src python + In []: C[1, 1:3] + In []: C[0:4, 0] + In []: C[1:5, 0] + #+end_src +* Question 4 + Obtain ~[[23, 24], [33, -34]]~ from ~C~ +* Solution 4 + #+begin_src python + In []: C[1:3, 2:4] + #+end_src +* Question 5 + Obtain the square in the center of the image +* Solution 5 + #+begin_src python + In []: imshow(I[75:225, 75:225]) + #+end_src +* Question 6 + Obtain the following + #+begin_src python + [[12, 0], [42, 0]] + [[12, 13, 14], [0, 0, 0]] + #+end_src + +* Solution 6 + #+begin_src python + In []: C[::3, 1::3] + In []: C[::4, 1:4] + #+end_src +* Summary + You should now be able to -- + - Manipulate 1D \& Multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slice and stride on arrays + - Read images into arrays and manipulate them. +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d getting-started-strings/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-strings/slides.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d getting-started-with-arrays/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-arrays/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,132 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. An array in Python is the same as a Python list + + a. True + #. False + +Answer: False + +2. ``x = array([1, 2, 3], [5, 6, 7])`` is a valid statement + + a. True + #. False + +Answer: False + +3. What will be the output of the following code, + :: + + x = array([[1, 2, 3], ['a', 2, 'c']]) + print x[0][0] + x[0][1] + x[0][2] + + a. 6 + #. 123 + #. a2c + #. Error as array takes only homogeneous elements + +Answer: 123 + +4. What will be the output of the following code, + :: + + x = [[1, 2, 3], [4.1, 4.2, 4.3], ['6','7',8]] + y = array(x) + print y[-1][-2] + y[-1][-1] + y[-2][0] + y[0][-2] + + a. 21.1 + #. 12.5 + #. 784.12 + #. Error as array takes only homogeneous elements + + .. 4.2 4.3 2 2 + +Answer: 784.12 + +5. What is the output of the following code, + :: + + x = array([[1, 2, 3], ['a', 2, 'c']]) + identity(x.shape) + + a. Will create an identity matrix of shape (2, 3). + #. ``identity()`` function takes an integer as argument and a tuple + is passed. + #. Will return, array([[1,0,1],[0,1,0]]) + #. Will return, array([[0,1,0],[0,1,0]]) + +Answer: ``identity()`` function takes an integer as argument and a + tuple is passed. + +6. ``ones_like()`` function? + + (A) Returns an array of ones with the same shape and type as a + given array. + (B) Return a new array of given shape and type, filled with ones. + + Read the statements and answer, + + a. Only statement A is correct. + #. Only statement B is correct. + #. Both statement A and B are correct. + #. Both statement A and B are incorrect. + +Answer: Only statement A is correct. + +7. ``zeros_like()`` function? + + (A) Return a new array of given shape and type, filled with zeros. + (B) Returns an array of zeros with the same shape and type as a + given array. + + + Read the statements and answer, + + a. Only statement A is correct. + #. Only statement B is correct. + #. Both statement A and B are correct. + #. Both statement A and B are incorrect. + +Answer: Only statement B is correct. + +8. What will be output of the following code snippet. + :: + + x = linspace(1,10,10).reshape(5,2) + print (x[-3]+x[-4]).sum() + + a. 10.0 + #. 18.0 + #. 14.0 + #. 16.44 + #. Error + +Answer: 18 + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Write a python script to create a 15x15 array of equally spaced 225 + elements from 1 to 1000, add 5 to each of the diagonal elements and + find the sum of all odd rows of the array. Say for example the + array, + :: + + x = array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + + will give answer 40 ((1+5) + 2 + 3 + 7 + 8 + (9+5)). + +2. For any given array([a1, a2, a3, .. , an]) the Vandermonde matrix + will be [[1, a1, a1**2, .. , a1**(n-1)], [1, a2, a2**2, .. , + a2**(n-1)], .. , [1, an, an**2, .. ,an**(n-1)]]. Write a python + script to generate the Vandermonde matrix and find the determinant + of the matrix for [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20]. [Hint: to find the determinant use the + function ``det()`` from ``linalg`` module.] diff -r e675f9208b91 -r 4054b1a6392d getting-started-with-arrays/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-arrays/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,324 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Create arrays using data +.. #. Create arrays from lists +.. #. Basic array operations +.. #. Creating identity matrix using ``identity()`` function. +.. #. Learn about ``zeros()``, ``zeros_like()``, ``ones()``, + ``ones_like()`` functions. + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` and ``pylab`` installed. +.. #. getting started with ``ipython``. +.. #. getting started with lists. + +.. Author: Anoop Jacob Thomas + Internal Reviewer : Puneeth + External Reviewer : + Checklist OK? : [2010-10-05] + +=========================== +Getting started with Arrays +=========================== + +.. #[Puneeth: Prerequisites and Objectives are missing. Fill them in] + +{{{ show the welcome slide }}} + +Welcome to the spoken tutorial on getting started with arrays. + +{{{ switch to next slide, outline slide }}} + +In this tutorial, we will learn about arrays, how to convert a list into an +array and also why an array is preferred over lists. And array operations. + +.. #[Puneeth: Fix the grammar above.] + +{{{ switch to next slide on overview of array }}} + +Arrays are homogeneous data structures, unlike lists, arrays cannot have +heterogeneous data elements, that is, it can have only one type of data +type, either all integers, or strings, or float, and not a mix. + +.. #[Puneeth: Use multiple short sentences, rather than one long sentence + I would've written something like this. + + Unlike lists, arrays are homogeneous data structures. They can have only + type of data, ....] + +Arrays are really fast in mathematical operations when compared to lists, +it is at least 80 to 100 times faster than lists. + +.. #[Puneeth: For what size of an array is that the comparison? + +{{{ switch to the next slide, creating arrays }}} + +Now let us see how to create arrays. + +I am assuming that you have your IPython interpreter running with the +``-pylab`` option, so that you have the required modules loaded. + +.. #[Puneeth: 'I am assuming' doesn't sound right. Ask them to open if it +.. is not open?] + +To create an array we will use the function ``array()`` as, + +:: + + a1 = array([1,2,3,4]) + +Notice that here we created a one dimensional array. Also notice the object +we passed to create an array. Now let us see how to create a two +dimensional array. Pause here and try to do it yourself before looking at +the solution. + +.. #[Puneeth: I don't think this question can be solved by an average +.. viewer. Questions during the tutorial, should generally be to re-iterate +.. concepts learnt? ] + +.. #[Puneeth: Also, you didn't even point out that we are converting a +.. list, using the ``array`` function. Bring the later section about +.. converting a list, here. A separate section is not necessary, IMHO.] + +This is how we create two dimensional arrays. + +:: + + a2 = array([[1,2,3,4],[5,6,7,8]]) + +.. #[Puneeth: Again, you could explain a bit about the fact that we are +.. converting a list of lists.] + +Let us see an easy method of creating an array with elements 1 to 8. + +:: + + ar = arange(1,9) + +.. #[Puneeth: say, creating the same array as before. for some time I got +.. confused .] + +And it created a single dimensional array of elements from 1 to 8. + +:: + + print ar + +.. #[Puneeth: be consistent with voice. say, we obtained... or something.] + +And how can we make it a two dimensional array of order 2 by 4. Pause here +and try to do it yourself, try ``ar.tab`` and find a suitable method for +that. + +{{{ switch to next slide, reshape() method }}} + +We can use the function ``reshape()`` for that purpose and it can be done +as, + +:: + + ar.reshape(2,4) + ar.reshape(4,2) + ar = ar.reshape(2,4) + +{{{ switch to next slide, creating array from list}}} + +Now, let us see how to convert a list object to an array. As you have +already seen, in both of the previous statements we have passed a list, so +creating an array can be done so, first let us create a list ``l1`` + +:: + + l1 = [1,2,3,4] + +Now we can convert the list to an array as, + +:: + + a3 = array(l1) + + +{{{ switch to the next slide, problem statement of unsolved exercise 1 }}} + +Create a three dimensional array of the order (2,2,4). + +.. #[Puneeth: s/order/shape or size ?] + +{{{ switch to the next slide, shape of an array }}} + +To find the shape of an array we can use the object ``.shape``, let us +check the shape of the arrays we have created so far, + +.. #[Puneeth: s/object/method ?] + +:: + + a1.shape + +``a1.shape`` object is a tuple, and since a1 is a single dimensional array, +it returned a tuple (4,). + +.. #[Puneeth: first show a 2D array, so that it becomes easier to explain. +.. Also, the word ``tuple`` need not be mentioned. ] + +{{{ switch to the next slide, unsolved exercise 2 }}} + +Find out the shape of the other arrays that we have created. + +.. #[Puneeth: solution missing.] + +{{{ Array can have only a single type of data }}} + +.. #[Puneeth: I guess, this whole section can be skipped. If you want to +.. keep this, just briefly mention that arrays are homogeneous in the +.. intro, don't explain it there.] + +Now let us try to create a new array with a mix of elements and see what +will happen, + +:: + + a4 = array([1,2,3,'a string']) + +Well, we expected an error as previously I said that an array can have only +homogeneous elements, but it didn't give an error. Let us check the values +in the new array created. In your IPython terminal type, +:: + + a4 + +Did you notice it, + +{{{ switch to next slide, implicit type casting }}} + +.. #[Puneeth: typecasting may be unnecessary. (Also too advanced?) an +.. average guy wouldn't use arrays with strings.] + +.. #[Puneeth: You may want to mention that float is the default dtype.] + +{{{ highlight all the array elements one by one using mouse movements }}} + +all the elements have been implicitly type casted as string, though our +first three elements were integers. + +.. #[Puneeth: when I type a4 it says some ``dtype`` etc. I don't understand +.. what it is, can you explain? ;)] + +{{{ switch to the next slide, identity & zeros methods }}} + +.. #[Puneeth: something needs to motivate this. why are we suddenly talking +.. of an identity matrix?] + +An identity matrix is a square matrix in which all the diagonal elements +are one and rest of the elements zero. We can create an identity matrix +using the method ``identity()``. + +The function ``identity()`` takes an integer argument, + +:: + + identity(3) + +As you can see the identity method returned a three by three square array +with all the diagonal elements as one and the rest of the elements as zero. + +.. #[Puneeth: You say array here, matrix there -- it's a bit messed up. +.. Clarify, explicitly.] + +``zeros()`` function accepts a tuple, which is the order of the array we +want to create, and it generates an array with all elements zero. + +{{{ switch to the next slide, problem statement of solved exercise 1 }}} + +Let us creates an array of the order four by five with all the elements +zero. We can do it using the method zeros, :: + + zeros((4,5)) + +Notice that we passed a tuple to the function zeros. + +{{{ switch to next slide, learning exercise }}} + +We learned two functions ``identity()`` and ``zeros()``, find out more +about the functions ``zeros_like()``, ``ones()``, ``ones_like()``. + +{{{ switch to next slide, array operations }}} + +Try the following, first check the value of a1, +:: + + a1 + +``a1`` is a single dimensional array, and now try, +:: + + a1 * 2 + +It returned a new array with all the elements multiplied by 2. +:: + + a1 + +note that the value of a1 still remains the same. + +Similarly with addition, +:: + + a1 + 2 + +it returns a new array, with all the elements summed with two. But +again notice that the value of a1 has not been changed. +:: + + a1 + +You may change the value of a1 by simply assigning the newly returned +array as, +:: + + a1 += 2 + +Notice the change in elements of a, +:: + + a + +We can use all the mathematical operations with arrays, Now let us try this +:: + + a1 = array([1,2,3,4]) + a2 = array([1,2,3,4]) + a1 + a2 + +Returns an array with element by element addition, +:: + + a1 * a2 + +Returns an array with element by element multiplication, notice that it +does not perform matrix multiplication. + +{{{ switch to next slide, summary slide }}} + +So this brings us to the end of this tutorial, in this tutorial we covered +basics of arrays, how to create an array, converting a list to an array, +basic array operations etc. + +.. #[Puneeth: s/how to create an array/creating an array] + +{{{ switch to next slide, thank you }}} + +Thank you! + +.. + Local Variables: + mode: rst + indent-tabs-mode: nil + sentence-end-double-space: nil + fill-column: 75 + End: diff -r e675f9208b91 -r 4054b1a6392d getting-started-with-arrays/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-arrays/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,132 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Getting started with arrays +#+AUTHOR: FOSSEE +#+EMAIL: info@fossee.in +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Arrays + - why arrays over lists + - Creating arrays + - Array operations + +* Overview of Arrays + - Arrays are homogeneous data structures. + - elements have to the same data type + - Arrays are faster compared to lists + - at least /80-100 times/ faster than lists + +* Creating Arrays + - Creating a 1-dimensional array + : In []: a1 = array([1, 2, 3, 4]) + - Creating a 2-dimensional array + : In []: a2 = array([[1,2,3,4],[5,6,7,8]]) + - Easier method of creating array with consecutive elements. + : In []: ar = arange(1,9) +* ~reshape()~ method + - To reshape an array + : In []: ar.reshape(2, 4) + : In []: ar.reshape(4, 2) + : In []: ar = ar.reshape(2, 4) + +* Creating ~array~ from ~list~. + - ~array()~ method accepts list as argument + - Creating a list + : In []: l1 = [1, 2, 3, 4] + - Creating an array + : In []: a3 = array(l1) + +* Exercise 1 + Create a 3-dimensional array of the order (2, 2, 4). + +* ~.shape~ of array + - ~.shape~ + To find the shape of the array + : In []: a1.shape + - ~.shape~ + returns a tuple of shape +* Exercise 2 + Find out the shape of the other arrays(a2, a3, ar) that we have created. +* Homogeneous data + - All elements in array should be of same type + : In []: a4 = array([1,2,3,'a string']) +* Implicit type casting + : In []: a4 + All elements are type casted to string type +* ~identity()~, ~zeros()~ methods + - ~identity(n)~ + Creates an identity matrix, a square matrix of order (n, n) with diagonal elements 1 and others 0. + - ~zeros((m, n))~ + Creates an ~m X n~ matrix with all elements 0. + +* Learning exercise + - Find out about + - ~zeros_like()~ + - ~ones()~ + - ~ones_like()~ + +* Array operations + - ~a1 * 2~ + returns a new array with all elements of ~a1~ multiplied by ~2~. + - Similarly ~+~, ~-~ \& ~/~. + - ~a1 + 2~ + returns a new array with all elements of ~a1~ summed with ~2~. + - ~a1 += 2~ + adds ~2~ to all elements of array ~a1~. + - Similarly ~-=~, ~*=~ \& ~/=~. + - ~a1 + a2~ + does elements-wise addition. + - Similarly ~-~, ~*~ \& ~/~. + - ~a1 * a2~ + does element-wise multiplication + + *Note* - array(A) * array(B) does element wise multiplication and not matrix multiplication + +* Summary + In this tutorial we covered, + - Basics of arrays + - Creating arrays + - Arrays from lists + - Basic array operations + +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d getting-started-with-arrays/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-arrays/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,277 @@ +% Created 2010-10-12 Tue 00:20 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Getting started with arrays} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Arrays + +\begin{itemize} +\item why arrays over lists +\end{itemize} + +\item Creating arrays +\item Array operations +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Overview of Arrays} +\label{sec-2} + +\begin{itemize} +\item Arrays are homogeneous data structures. + +\begin{itemize} +\item elements have to the same data type +\end{itemize} + +\item Arrays are faster compared to lists + +\begin{itemize} +\item at least \emph{80-100 times} faster than lists +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Creating Arrays} +\label{sec-3} + +\begin{itemize} +\item Creating a 1-dimensional array +\end{itemize} + +\begin{verbatim} + In []: a1 = array([1, 2, 3, 4]) +\end{verbatim} + +\begin{itemize} +\item Creating a 2-dimensional array +\end{itemize} + +\begin{verbatim} + In []: a2 = array([[1,2,3,4],[5,6,7,8]]) +\end{verbatim} + +\begin{itemize} +\item Easier method of creating array with consecutive elements. +\end{itemize} + +\begin{verbatim} + In []: ar = arange(1,9) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{reshape()} method} +\label{sec-4} + +\begin{itemize} +\item To reshape an array +\end{itemize} + +\begin{verbatim} + In []: ar.reshape(2, 4) + In []: ar.reshape(4, 2) + In []: ar = ar.reshape(2, 4) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Creating \texttt{array} from \texttt{list}.} +\label{sec-5} + +\begin{itemize} +\item \texttt{array()} method accepts list as argument +\item Creating a list +\begin{verbatim} + In []: l1 = [1, 2, 3, 4] +\end{verbatim} + +\item Creating an array +\begin{verbatim} + In []: a3 = array(l1) +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 1} +\label{sec-6} + + Create a 3-dimensional array of the order (2, 2, 4). +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{.shape} of array} +\label{sec-7} + +\begin{itemize} +\item \texttt{.shape} + To find the shape of the array +\begin{verbatim} + In []: a1.shape +\end{verbatim} + +\item \texttt{.shape} + returns a tuple of shape +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 2} +\label{sec-8} + + Find out the shape of the other arrays(a2, a3, ar) that we have created. +\end{frame} +\begin{frame}[fragile] +\frametitle{Homogeneous data} +\label{sec-9} + +\begin{itemize} +\item All elements in array should be of same type +\begin{verbatim} + In []: a4 = array([1,2,3,'a string']) +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Implicit type casting} +\label{sec-10} + +\begin{verbatim} + In []: a4 +\end{verbatim} + + All elements are type casted to string type +\end{frame} +\begin{frame} +\frametitle{\texttt{identity()}, \texttt{zeros()} methods} +\label{sec-11} + +\begin{itemize} +\item \texttt{identity(n)} + Creates an identity matrix, a square matrix of order (n, n) with diagonal elements 1 and others 0. +\item \texttt{zeros((m, n))} + Creates an \texttt{m X n} matrix with all elements 0. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Learning exercise} +\label{sec-12} + +\begin{itemize} +\item Find out about + +\begin{itemize} +\item \texttt{zeros\_like()} +\item \texttt{ones()} +\item \texttt{ones\_like()} +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Array operations} +\label{sec-13} + +\begin{itemize} +\item \texttt{a1 * 2} + returns a new array with all elements of \texttt{a1} multiplied by \texttt{2}. + +\begin{itemize} +\item Similarly \texttt{+}, \texttt{-} \& \texttt{/}. +\end{itemize} + +\item \texttt{a1 + 2} + returns a new array with all elements of \texttt{a1} summed with \texttt{2}. +\item \texttt{a1 += 2} + adds \texttt{2} to all elements of array \texttt{a1}. + +\begin{itemize} +\item Similarly \texttt{-=}, \texttt{*=} \& \texttt{/=}. +\end{itemize} + +\item \texttt{a1 + a2} + does elements-wise addition. + +\begin{itemize} +\item Similarly \texttt{-}, \texttt{*} \& \texttt{/}. +\end{itemize} + +\item \texttt{a1 * a2} + does element-wise multiplication +\end{itemize} + + + \textbf{Note} - array(A) * array(B) does element wise multiplication and not matrix multiplication +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-14} + + In this tutorial we covered, +\begin{itemize} +\item Basics of arrays +\item Creating arrays +\item Arrays from lists +\item Basic array operations +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-15} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d getting-started-with-for/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-for/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,115 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. In Python a block is represented by + + a. Curly braces + #. Begin and End keywords + #. Indentation + #. Curly braces + Indentation + #. All of the above + +Answer: Indentation + +2. Indentation is not mandatory in Python + + a. True + #. False + +Answer: False + +3. A ``for`` loop in Python, + + a. is a simple iterator + #. is a condition based loop + #. can iterate only over integer list of elements + #. All of the above + +Answer: is a simple iterator + +4. ``range()`` function can generate negative numbers + + a. True + #. False + +Answer: True + +5. ``range(a,b)`` function returns, + + a. A tuple of elements from a to b including a and b + #. A tuple of elements from a to b excluding b + #. A list of elements from a to b including a and b + #. A list of elements from a to b excluding b + +Answer: A list of elements from a to b excluding b + +6. ``linspace(1,100,2)`` and ``range(1,100,2)`` produces the same output, + + a. True + #. False + +Answer: False + +7. What is the output of the below code snippet? + :: + + y = 1 + for x in range(21): + y*=x + print y + + a. Product of natural numbers up to 20(including) + #. Product of natural numbers up to 21(including) + #. Zero + #. Error + +Answer: Zero + +8. What is the output of the below code snippet? + :: + + y = 1 + for x in range(1,21): + y*=x + print y + + a. Product of natural numbers up to 20(including) + #. Product of natural numbers up to 21(including) + #. Zero + #. Error + +Answer: Product of natural numbers up to 20(including) + +9. What is the output of the below code snippet? + :: + + y = 1 + for x in range(1,21) + y*=x + print y + + a. Product of natural numbers up to 20(including) + #. Product of natural numbers up to 21(including) + #. Zero + #. Error + +Answer: Error + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Write a python script to calculate the sum of the first 1000 + natural numbers? + +2. Write a python script to find out prime numbers up to 500. + [`hint`: a number ``A`` which is divisible by only ``1`` and ``A`` + is a prime number.] + +3. Write a python script to find out the difference between the + square of sum of first 100 natural numbers and sum of squares of + first 100 natural numbers. + diff -r e675f9208b91 -r 4054b1a6392d getting-started-with-for/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-for/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,304 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Write blocks of code in python. +.. #. Use for loop. +.. #. Use ``range()`` function. +.. #. Write blocks in python interpreter +.. #. Write blocks in ipython interpreter. + + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` and ``pylab`` installed. +.. #. getting started with ``ipython``. +.. #. getting started with lists. + + +.. Author : Anoop Jacob Thomas + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + + +============================= +Getting started with for loop +============================= + +{{{ show welcome slide }}} + +Hello and welcome to the tutorial getting started with ``for`` loop. + +{{{ switch to next slide, outline slide }}} + +In this tutorial we will learn about ``for`` loops in python, and also +learn how to write blocks of code in Python. + +.. #[Nishanth]: Instead of saying basics of indenting code, + say How to define code blocks in Python + +{{{ switch to next slide, about whitespaces }}} + +In Python whitespace is significant, and the blocks are visually +separated. + +.. #[nishanth]: Simply tell how blocks are defined in python. + The details like braces are not used and its + advantages like neat code can be told after completely + explaining the indentation + +.. #[Amit]: Do you want to do that here. May be its better to talk about + this after some initiation into the idea of blocks. + +The best practice is to indent the code using four spaces. + +.. #[Nishanth]: Even this detail may be skipped. Simply say use 4 spaces + for indentation. Do that while typing so that they can + actually see what is being typed. + +As you can see in the slide, ``Block B`` is an inner block and it is +indented using 4 spaces, and after ``Block B`` the next statement in +``Block A`` starts from the same indentation level of other ``Block +A`` statements. + +Now let us move straight into ``for`` loop. + +{{{ switch to next slide, problem statement of exercise 1 }}} + + +Write a for loop which iterates through a list of numbers and find the +square root of each number. +:: + + numbers are 1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916 + +.. #[nishanth]: making new list with square roots induces extra complication + like appending which has no use case here + +.. #[Nishanth]: The problem focuses more on square root and creation + of list. The problem must be simple and focusing on + nothing more but the indentation and for loop. + May be change the problem to print squares than to + print square roots. + +For the problem, first we need to create a ``list`` of numbers and +then iterate over the list and find the square root of each element in +it. And let us create a script, rather than typing it out in the +interpreter itself. Create a script called list_roots.py and type the +following. + +{{{ open the text editor and paste the following code there }}} +:: + + numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] + for each in numbers: + print "Square root of", each, "is", sqrt(each) + print "This is not in for loop!" + +.. numbers = [1, 12, 3, 4, 21, 17] + for each in numbers: + print each, each * each + +.. #[nishanth]: I don't see a use case to append the sq_root to + square_roots. It is only complicating stuff. + Simply iterate and print. + +{{{ switch to next slide, save and run script }}} + +{{{ save the script }}} + +Now save the script, and run it from your IPython interpreter. I +assume that you have started your IPython interpreter using ``-pylab`` +option. + +Run the script as, +:: + + %run -i list_roots.py + +.. #[Nishanth]: you don't have to use the -i option here + +{{{ run the script }}} + +So that was easy! All what we did was iterate over the list element by +element and then use the element for calculation. Note that here we +used two variables. One the variable ``numbers``, which is a list, +another one ``each``, which is the element of list under consideration +in each cycle of the ``for`` loop. The variable names can be chosen by +you. + +.. #[Nishanth]: The details like we didn't have to find the length + are relevant for people who have programmed in C or + other languages earlier. But for a newbie it is more + of confusing extra info. That part may be skipped. + Simply go ahead and focus on the syntax of for loop. + And how the variable name is used inside the for loop. + If you modify the question to only print, the extra + variable sq_root can also be avoided. let it be more + about "each", "numbers" and "for". no other new names. + +{{{ show the script which was created }}} + +Note that the lines after ``for`` statement, is indented using four +spaces. + +{{{ highlight the line after for statement }}} + +It means that line is part of the for loop. And it is a block of code, +although it is only a single statement in the block. And the fourth +line or the immediate line after the ``for`` block is not indented, + +{{{ highlight the fourth line - the line just after for loop }}} + +it means that it is not part of the ``for`` loop and the lines after +that doesn't fall in the scope of the ``for`` loop. Thus each block is +separated by the indentation level. Thus marking the importance of +white-spaces in Python. + +{{{ switch to the slide which shows the problem statement of the first +problem to be tried out }}} + +Now a question for you to try, from the given numbers make a list of +perfect squares and a list of those which are not. The numbers are, +:: + + 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, 7056, 576, 2916 + +{{{ switch to next slide, problem statement of second problem in +solved exercise}}} + +Now let us try a simple one, to print the square root of numbers in +the list. And this time let us do it right in the IPython +interpreter. + +{{{ switch to next slide, Indentation in ``ipython`` }}} + +{{{ switch focus to the IPython interpreter }}} + +So let us start with making a list. Type the following +:: + + numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] + for each in numbers: + +and now you will notice that, as soon as you press the return key +after for statement, the prompt changes to four dots and the cursor is +not right after the four dots but there are four spaces from the +dots. Please note that IPython automatically indents the block. The +four dots tell you that you are inside a block. Now type the rest of +the ``for`` loop, + +{{{ switch to next slide, Indentation in ``ipython`` (cont'd) }}} + +.. #[Nishanth]: Tell that IPython does auto indentation. + +:: + + print "Square root of", each, + print "is", sqrt(each) + +Now we have finished the statements in the block, and still the +interpreter is showing four dots, which means you are still inside the +block. To exit from the block press return key or the enter key twice +without entering anything else. It printed the square root of each +number in the list, and that is executed in a ``for`` loop. + +{{{ switch to next slide, Indentation in ``python`` interpreter }}} + +Now, let us find the cube of all the numbers from one to ten. But this +time let us try it in the vanilla version of Python interpreter. + +Start the vanilla version of Python interpreter by issuing the command +``python`` in your terminal. + +{{{ open the python interpreter in the terminal using the command +python to start the vanilla Python interpreter }}} + +{{{ switch to next slide, Indentation in ``python`` interpreter +(cont'd) }}} + +Start with, +:: + + for i in range(1,11): + +and press enter once, and we will see that this time it shows four +dots, but the cursor is close to the dots, so we have to indent the +block. The vanilla version of Python interpreter does not indent the +code automatically. So enter four spaces there and then type the +following +:: + + print i, "cube is", i**3 + +Now when we hit enter, we still see the four dots, to get out of the +block, hit enter once again + +.. #[Nishanth]: Here also the overhead on print can be reduced. + Think of a simple print statement. This statement + will be confusing for a newbie. + We can focus more on indentation in python. + +.. #[nishanth]: Not sure if you must use range here. You can + define a list of numbers and iterate on it. + Then say this list can also be generated using + the range function and hence introduce range. + +{{{ switch to the next slide, ``range()`` function }}} + +Okay! so the main thing here we learned is how to use Python +interpreter and IPython interpreter to specify blocks. But while we +were generating the multiplication table we used something new, +``range()`` function. ``range()`` is an inbuilt function in Python +which can be used to generate a ``list`` of integers from a starting +number to an ending number. Note that the ending number that you +specify will not be included in the ``list``. + +.. #[Nishanth]: Show some examples of range without the step argument + May be give an exercise with negative numbers as arguments + +{{{ switch to next slide, problem statement of the next problem in +solved exercises }}} + +Now, let us print all the odd numbers from 1 to 50. Pause here and try +to solve the problem yourself. + +Let us do it in our IPython interpreter for ease of use. + +{{{ switch focus to ipython interpreter }}} + +The problem can be solved by just using the ``range()`` function. + +It can be solved as, +:: + + print range(1,51,2) + +This time we passed three parameters to ``range()`` function unlike +the previous case where we passed only two parameters. The first two +parameters are the same in both the cases. The first parameter is the +starting number of the sequence and the second parameter is the end of +the range. Note that the sequence doesn't include the ending +number. The third parameter is for stepping through the sequence. Here +we gave two which means we are skipping every alternate element. + +{{{ switch to next slide, summary slide }}} + +Thus we come to the end of this tutorial. We learned about blocks in +Python, indentation, blocks in IPython, for loop, iterating over a +list and then the ``range()`` function. + +.. #[Amit]: There does seem to too much overhead of details. Should + the first example be done using script is it necessary. + Do add some things in evolutionary manner. Like introducing + range as a list and doing a very very simple for loop.Like + iterating over [1,2,3] .Before getting into a problem. + And club details about problem in one paragraph and syntactic details + in other. + +{{{ switch to next slide, thank you slide }}} + +Thank you! diff -r e675f9208b91 -r 4054b1a6392d getting-started-with-for/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-for/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,146 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Getting started with for +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - ~for~ loop in Python. + - Blocks of code in Python. + - Indentation +* Whitespace in Python + - Whitespace is significant + - blocks are visually separated + - Blocks are indented using 4 spaces + : Block A + : Block A + : Block B + : Block B + : Block A + ~Block B~ is an inner block and is indented using 4 spaces +* Exercise 1 + Write a ~for~ loop which iterates through a list of numbers and find + the square root of each number. + : + The numbers are, + : 1369, 7225, 3364, 7056, 5625, 729, 7056, + : 576, 2916 +* Solution 1 + - Open text editor and type the following code + #+begin_src python + numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, + 576, 2916] + + for each in numbers: + print "Square root of", each, "is", sqrt(each) + + print "This is not in for loop!" + #+end_src +* Save \& run script + - Save the script as ~list_roots.py~ + - Run in ~ipython~ interpreter as, + : In []: %run -i list_roots.py +* Exercise 2 + From the given numbers make a list of perfect squares and a list of those which are not. + : + The numbers are, + : 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, + : 7056, 576, 2916 +* Exercise 3 (indentation in ~ipython~) + Print the square root of numbers in the list. + : + Numbers are, + : 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, + : 7056, 576, 2916 +* Indentation in ~ipython~ + : In []: numbers = [1369, 7225, 3364, 7056, 5625, + : ...: 729, 7056, 576, 2916] + + : In []: for each in numbers: + : ...: + Note the four spaces here + : + : + : + : + : + : +* Indentation in ~ipython~ (cont'd) + : In []: numbers = [1369, 7225, 3364, 7056, 5625, + : ...: 729, 7056, 576, 2916] + : In []: for each in numbers: + : ...: + Note the four spaces here + : + Now type the rest of the code + : ...: print "Square root of", each, + : ...: print "is", sqrt(each) + : ...: + : ...: +* Indentation in ~python~ interpreter + Find out the cube of all the numbers from 1 to 10. + : + /do it in the python interpreter/ +* Indentation in ~python~ interpreter (cont'd) + #+begin_src python + >>> for i in range(1, 11): + ... print i, "cube is", i**3 + ... + #+end_src +* ~range()~ function + - in built function in Python + - generates a list of integers + - /syntax:/ range([start,] stop[, step]) + - /example:/ + - range(1, 20) - /generates integers from 1 to 20/ + - range(20) - /generates integers from 0 to 20/ +* Exercise 4 + Print all the odd numbers from 1 to 50. +* Summary + - blocks in ~python~ + - indentation + - blocks in ~ipython~ interpreter + - ~for~ loop + - iterating over list using ~for~ loop + - ~range()~ function +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d getting-started-with-for/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/getting-started-with-for/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,285 @@ +% Created 2010-10-12 Tue 12:55 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Getting started with for} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item \texttt{for} loop in Python. +\item Blocks of code in Python. + +\begin{itemize} +\item Indentation +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Whitespace in Python} +\label{sec-2} + +\begin{itemize} +\item Whitespace is significant + +\begin{itemize} +\item blocks are visually separated +\end{itemize} + +\item Blocks are indented using 4 spaces +\begin{verbatim} + Block A + Block A + Block B + Block B + Block A +\end{verbatim} + + \texttt{Block B} is an inner block and is indented using 4 spaces +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 1} +\label{sec-3} + + Write a \texttt{for} loop which iterates through a list of numbers and find + the square root of each number. +\begin{verbatim} + +\end{verbatim} + + The numbers are, +\begin{verbatim} + 1369, 7225, 3364, 7056, 5625, 729, 7056, + 576, 2916 +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-4} + +\begin{itemize} +\item Open text editor and type the following code +\end{itemize} + +\begin{verbatim} +numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, + 576, 2916] + +for each in numbers: + print "Square root of", each, "is", sqrt(each) + +print "This is not in for loop!" +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Save \& run script} +\label{sec-5} + +\begin{itemize} +\item Save the script as \texttt{list\_roots.py} +\item Run in \texttt{ipython} interpreter as, +\begin{verbatim} + In []: %run -i list_roots.py +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 2} +\label{sec-6} + + From the given numbers make a list of perfect squares and a list of those which are not. +\begin{verbatim} + +\end{verbatim} + + The numbers are, +\begin{verbatim} + 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, + 7056, 576, 2916 +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 3 (indentation in \texttt{ipython})} +\label{sec-7} + + Print the square root of numbers in the list. +\begin{verbatim} + +\end{verbatim} + + Numbers are, +\begin{verbatim} + 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, + 7056, 576, 2916 +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Indentation in \texttt{ipython}} +\label{sec-8} + +\begin{verbatim} + In []: numbers = [1369, 7225, 3364, 7056, 5625, + ...: 729, 7056, 576, 2916] +\end{verbatim} + + +\begin{verbatim} + In []: for each in numbers: + ...: +\end{verbatim} + + Note the four spaces here +\begin{verbatim} + + + + + + +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Indentation in \texttt{ipython} (cont'd)} +\label{sec-9} + +\begin{verbatim} + In []: numbers = [1369, 7225, 3364, 7056, 5625, + ...: 729, 7056, 576, 2916] + In []: for each in numbers: + ...: +\end{verbatim} + + Note the four spaces here +\begin{verbatim} + +\end{verbatim} + + Now type the rest of the code +\begin{verbatim} + ...: print "Square root of", each, + ...: print "is", sqrt(each) + ...: + ...: +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Indentation in \texttt{python} interpreter} +\label{sec-10} + + Find out the cube of all the numbers from 1 to 10. +\begin{verbatim} + +\end{verbatim} + + \emph{do it in the python interpreter} +\end{frame} +\begin{frame}[fragile] +\frametitle{Indentation in \texttt{python} interpreter (cont'd)} +\label{sec-11} + +\begin{verbatim} +>>> for i in range(1, 11): +... print i, "cube is", i**3 +... +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{\texttt{range()} function} +\label{sec-12} + +\begin{itemize} +\item in built function in Python +\item generates a list of integers + +\begin{itemize} +\item \emph{syntax:} range([start,] stop[, step]) +\item \emph{example:} + +\begin{itemize} +\item range(1, 20) - \emph{generates integers from 1 to 20} +\item range(20) - \emph{generates integers from 0 to 20} +\end{itemize} + +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 4} +\label{sec-13} + + Print all the odd numbers from 1 to 50. +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-14} + +\begin{itemize} +\item blocks in \texttt{python} +\item indentation +\item blocks in \texttt{ipython} interpreter +\item \texttt{for} loop +\item iterating over list using \texttt{for} loop +\item \texttt{range()} function +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-15} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d getting_started_with_arrays.rst --- a/getting_started_with_arrays.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,213 +0,0 @@ -.. 4.1 LO: getting started with arrays (2) [anoop] -.. ------------------------------------------------ -.. * why arrays -.. + speed - simply say -.. + array level operations -.. * creating arrays -.. + direct data -.. + list conversion -.. + homogeneous -.. + builtins - identitiy, zeros, -.. * array operations -.. + =+ - * /= - -=========================== -Getting started with Arrays -=========================== - -{{{ show the welcome slide }}} - -Welcome to the spoken tutorial on getting started with arrays. - -{{{ switch to next slide, outline slide }}} - -In this tutorial, we will learn about arrays, how to convert a list -into an array and also why an array is preferred over lists. And array -operations. - -{{{ switch to next slide on overview of array }}} - -Arrays are homogeneous data structures, unlike lists, arrays cannot -have heterogeneous data elements, that is, it can have only one type -of data type, either all integers, or strings, or float, and not a -mix. - -Arrays are really fast in mathematical operations when compared to -lists, it is at least 80 to 100 times faster than lists. - -{{{ switch to the next slide, creating arrays }}} - -I am assuming that you have your IPython interpreter running with the -``-pylab`` option, so that you have the required modules loaded. - -To create an array we will use the function ``array()`` as, -:: - - a1 = array([1,2,3,4]) - -Notice that here we created a one dimensional array. Also notice the -object we passed to create an array. Now let us see how to create a -two dimensional array. -:: - - a2 = array([[1,2,3,4],[5,6,7,8]]) - -Now, let us see how to convert a list object to an array. As you have -already seen, in both of the previous statements we have passed a -list, so creating an array can be done so, first let us create a list -``l1`` -:: - - l1 = [1,2,3,4] - -Now we can convert the list to an array as, -:: - - a3 = array(l1) - - -{{{ switch to the next slide, problem statement of unsolved exercise 1 }}} - -Create a three dimensional array of the order (2,2,4). - -{{{ switch to the next slide, shape of an array }}} - -To find the shape of an array we can use the object ``.shape``, let us -check the shape of the arrays we have created so far, -:: - - a1.shape - -``a1.shape`` object is a tuple, and since a1 is a single dimensional -array, it returned a tuple (4,). - -{{{ switch to the next slide, unsolved exercise 2 }}} - -Find out the shape of the other two arrays that we have created. - -{{{ Array can have only a single type of data }}} - -Now let us try to create a new array with a mix of elements and see -what will happen, -:: - - a4 = array([1,2,3,'a string']) - -Well, we expected an error as previously I said that an array can have -only homogeneous elements, but it didn't give an error. Let us check -the values in the new array created. In your IPython terminal type, -:: - - a4 - -Did you notice it, - -{{{ highlight all the array elements one by one using mouse -movements }}} - -all the elements have been implicitly type casted as string, though -our first three elements were integers. - -{{{ switch to the next slide, identity & zeros methods }}} - -An identity matrix is a square matrix in which all the diagonal -elements are one and rest of the elements zero. We can create an -identity matrix using the method ``identity()``. - -The function ``identity()`` takes an integer argument, -:: - - identity(3) - -As you can see the identity method returned a three by three square -array with all the diagonal elements as one and the rest of the -elements as zero. - -``zeros()`` function accepts a tuple, which is the order of the array -we want to create, and it generates an array with all elements zero. - -{{{ switch to the next slide, problem statement of the solved exercise -1 }}} - -Let us creates an array of the order four by five with all the -elements zero. We can do it using the method zeros, -:: - - zeros((4,5)) - -Notice that we passed a tuple to the function zeros. - -{{{ switch to next slide, learning exercise }}} - -We learned two functions ``identity()`` and ``zeros()``, find out more -about the functions ``zeros_like()``, ``ones()``, ``ones_like()``. - -{{{ switch to next slide, array operations }}} - -Try the following, first check the value of a1, -:: - - a1 - -``a1`` is a single dimensional array, and now try, -:: - - a1 * 2 - -It returned a new array with all the elements multiplied by 2. -:: - - a1 - -note that the value of a1 still remains the same. - -Similarly with addition, -:: - - a1 + 2 - -it returns a new array, with all the elements summed with two. But -again notice that the value of a1 has not been changed. -:: - - a1 - -You may change the value of a1 by simply assigning the newly returned -array as, -:: - - a1 += 2 - -Notice the change in elements of a, -:: - - a - -We can use all the mathematical operations with arrays, Now let us try -this -:: - - a1 = array([1,2,3,4]) - a2 = array([1,2,3,4]) - a1 + a2 - -Returns an array with element by element addition, -:: - - a1 * a2 - -Returns an array with element by element multiplication, notice that -it does not perform matrix multiplication. - -{{{ switch to next slide, recap slide }}} - -So this brings us to the end of this tutorial, in this tutorial we covered basics of arrays, how to create an array, converting a list to an array, basic array operations etc. - -{{{ switch to next slide, thank you }}} - -Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: diff -r e675f9208b91 -r 4054b1a6392d getting_started_with_for.rst --- a/getting_started_with_for.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,272 +0,0 @@ -.. 3.2 LO: getting started with =for= (2) [anoop] -.. ----------------------------------------------- -.. * blocks in python -.. + (indentation) -.. * blocks in ipython -.. + ... prompt -.. + hitting enter -.. * =for= with a list -.. * =range= function - -============================= -Getting started with for loop -============================= - -{{{ show welcome slide }}} - -Hello and welcome to the tutorial getting started with ``for`` loop. - -{{{ switch to next slide, outline slide }}} - -In this tutorial we will learn about ``for`` loops in python, and also -learn how to write blocks of code in Python. - -.. #[Nishanth]: Instead of saying basics of indenting code, - say How to define code blocks in Python - -{{{ switch to next slide, about whitespaces }}} - -In Python whitespace is significant, and the blocks are visually -separated. - -.. #[nishanth]: Simply tell how blocks are defined in python. - The details like braces are not used and its - advantages like neat code can be told after completely - explaining the indentation - -.. #[Amit]: Do you want to do that here. May be its better to talk about - this after some initiation into the idea of blocks. - -The best practice is to indent the code using four spaces. - -.. #[Nishanth]: Even this detail may be skipped. Simply say use 4 spaces - for indentation. Do that while typing so that they can - actually see what is being typed. - -Now let us move straight into ``for`` loop. - -{{{ switch to next slide, problem statement of exercise 1 }}} - - -Write a for loop which iterates through a list of numbers and find the -square root of each number. -:: - - numbers are 1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916 - -.. #[nishanth]: making new list with square roots induces extra complication - like appending which has no use case here - -.. #[Nishanth]: The problem focuses more on square root and creation - of list. The problem must be simple and focusing on - nothing more but the indentation and for loop. - May be change the problem to print squares than to - print square roots. - -For the problem, first we need to create a ``list`` of numbers and -then iterate over the list and find the square root of each element in -it. And let us create a script, rather than typing it out in the -interpreter itself. Create a script called list_roots.py and type the -following. - -{{{ open the text editor and paste the following code there }}} -:: - - numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] - for each in numbers: - print "Square root of", each, "is", sqrt(each) - print "This is not in for loop!" - -.. numbers = [1, 12, 3, 4, 21, 17] - for each in numbers: - print each, each * each - -.. #[nishanth]: I don't see a use case to append the sq_root to - square_roots. It is only complicating stuff. - Simply iterate and print. - -{{{ save the script }}} - -Now save the script, and run it from your IPython interpreter. I -assume that you have started your IPython interpreter using ``-pylab`` -option. - -Run the script as, -:: - - %run -i list_roots.py - -.. #[Nishanth]: you don't have to use the -i option here - -{{{ run the script }}} - -So that was easy! All what we did was iterate over the list element by -element and then use the element for calculation. Note that here we -used two variables. One the variable ``numbers``, which is a list, -another one ``each``, which is the element of list under consideration -in each cycle of the ``for`` loop. The variable names can be chosen by -you. - -.. #[Nishanth]: The details like we didn't have to find the length - are relevant for people who have programmed in C or - other languages earlier. But for a newbie it is more - of confusing extra info. That part may be skipped. - Simply go ahead and focus on the syntax of for loop. - And how the variable name is used inside the for loop. - If you modify the question to only print, the extra - variable sq_root can also be avoided. let it be more - about "each", "numbers" and "for". no other new names. - -{{{ show the script which was created }}} - -Note that the lines after ``for`` statement, is indented using four -spaces. - -{{{ highlight the line after for statement }}} - -It means that line is part of the for loop. And it is a block of code, -although it is only a single statement in the block. And the fourth -line or the immediate line after the ``for`` block is not indented, - -{{{ highlight the fourth line - the line just after for loop }}} - -it means that it is not part of the ``for`` loop and the lines after -that doesn't fall in the scope of the ``for`` loop. Thus each block is -separated by the indentation level. Thus marking the importance of -white-spaces in Python. - -{{{ switch to the slide which shows the problem statement of the first -problem to be tried out }}} - -Now a question for you to try, from the given numbers make a list of -perfect squares and a list of those which are not. The numbers are, -:: - - 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, 7056, 576, 2916 - -{{{ switch to next slide, problem statement of second problem in -solved exercise}}} - -Now let us try a simple one, to print the square root of numbers in -the list. And this time let us do it right in the IPython -interpreter. - -{{{ switch focus to the IPython interpreter }}} - -So let us start with making a list. Type the following -:: - - numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] - for each in numbers: - -and now you will notice that, as soon as you press the return key -after for statement, the prompt changes to four dots and the cursor is -not right after the four dots but there are four spaces from the -dots. Please note that IPython automatically indents the block. The -four dots tell you that you are inside a block. Now type the rest of -the ``for`` loop, - -.. #[Nishanth]: Tell that IPython does auto indentation. - -:: - - print "Square root of", each, "is", sqrt(each) - -Now we have finished the statements in the block, and still the -interpreter is showing four dots, which means you are still inside the -block. To exit from the block press return key or the enter key twice -without entering anything else. It printed the square root of each -number in the list, and that is executed in a ``for`` loop. - -Now, let us find the cube of all the numbers from one to ten. But this -time let us try it in the vanilla version of Python interpreter. - -Start the vanilla version of Python interpreter by issuing the command -``python`` in your terminal. - -{{{ open the python interpreter in the terminal using the command -python to start the vanilla Python interpreter }}} - -Start with, -:: - - for i in range(1,11): - -and press enter once, and we will see that this time it shows four -dots, but the cursor is close to the dots, so we have to indent the -block. The vanilla version of Python interpreter does not indent the -code automatically. So enter four spaces there and then type the -following -:: - - print i, "cube is", i**3 - -Now when we hit enter, we still see the four dots, to get out of the -block, hit enter once again - -.. #[Nishanth]: Here also the overhead on print can be reduced. - Think of a simple print statement. This statement - will be confusing for a newbie. - We can focus more on indentation in python. - -.. #[nishanth]: Not sure if you must use range here. You can - define a list of numbers and iterate on it. - Then say this list can also be generated using - the range function and hence introduce range. - -Okay! so the main thing here we learned is how to use Python -interpreter and IPython interpreter to specify blocks. But while we -were generating the multiplication table we used something new, -``range()`` function. ``range()`` is an inbuilt function in Python -which can be used to generate a ``list`` of integers from a starting -number to an ending number. Note that the ending number that you -specify will not be included in the ``list``. - -.. #[Nishanth]: Show some examples of range without the step argument - May be give an exercise with negative numbers as arguments - -Now, let us print all the odd numbers from 1 to 50. Let us do it in -our IPython interpreter for ease of use. - -{{{ switch to next slide, problem statement of the next problem in -solved exercises }}} - -{{{ switch focus to ipython interpreter }}} - -The problem can be solved by just using the ``range()`` function. - -It can be solved as, -:: - - print range(1,51,2) - -This time we passed three parameters to ``range()`` function unlike -the previous case where we passed only two parameters. The first two -parameters are the same in both the cases. The first parameter is the -starting number of the sequence and the second parameter is the end of -the range. Note that the sequence doesn't include the ending -number. The third parameter is for stepping through the sequence. Here -we gave two which means we are skipping every alternate element. - -{{{ switch to next slide, recap slide }}} - -Thus we come to the end of this tutorial. We learned about blocks in -Python, indentation, blocks in IPython, for loop, iterating over a -list and then the ``range()`` function. - -.. #[Amit]: There does seem to too much overhead of details. Should - the first example be done using script is it necessary. - Do add some things in evolutionary manner. Like introducing - range as a list and doing a very very simple for loop.Like - iterating over [1,2,3] .Before getting into a problem. - And club details about problem in one paragraph and syntactic details - in other. - -{{{ switch to next slide, thank you slide }}} - -Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: Nishanth - Reviewer 2: Amit Sethi - External reviewer: diff -r e675f9208b91 -r 4054b1a6392d gettings_started_with_for.rst --- a/gettings_started_with_for.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,217 +0,0 @@ -.. 3.2 LO: getting started with =for= (2) [anoop] -.. ----------------------------------------------- -.. * blocks in python -.. + (indentation) -.. * blocks in ipython -.. + ... prompt -.. + hitting enter -.. * =for= with a list -.. * =range= function - -============================= -Getting started with for loop -============================= - -{{{ show welcome slide }}} - -Hello and welcome to the tutorial getting started with ``for`` loop. - -{{{ switch to next slide, outline slide }}} - -In this tutorial we will see ``for`` loops in python, and also cover -the basics of indenting code in python. - -{{{ switch to next slide, about whitespaces }}} - -In Python whitespace is significant, and the blocks are visually -separated rather than using braces or any other mechanisms for -defining blocks. And by this method Python forces the programmers to -stick on to one way of writing or beautifying the code rather than -debating over where to place the braces. This way it produces uniform -code than obscure or unreadable code. - -A block may be defined by a suitable indentation level which can be -either be a tab or few spaces. And the best practice is to indent the -code using four spaces. - -Now let us move straight into ``for`` loop. - -{{{ switch to next slide, problem statement of exercise 1 }}} - -Write a for loop which iterates through a list of numbers and find the -square root of each number. Also make a new list with the square roots -and print it at the end. -:: - - numbers are 1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916 - -For the problem, first we need to create a ``list`` of numbers and -then iterate over the list and find the square root of each element in -it. And let us create a script, rather than typing it out in the -interpreter itself. Create a script called list_roots.py and type the -following. - -{{{ open the text editor and paste the following code there }}} -:: - - numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] - square_roots = [] - for each in numbers: - sq_root = sqrt(each) - print "Square root of", each, "is", sq_root - square_roots.append(sq_root) - print - print square_roots - -{{{ save the script }}} - -Now save the script, and run it from your IPython interpreter. I -assume that you have started your IPython interpreter using ``-pylab`` -option. - -Run the script as, -:: - - %run -i list_roots.py - -{{{ run the script }}} - -So that was easy! We didn't have to find the length of the string nor -address of each element of the list one by one. All what we did was -iterate over the list element by element and then use the element for -calculation. Note that here we used three variables. One the variable -``numbers``, which is a list, another one ``each``, which is the -element of list under consideration in each cycle of the ``for`` loop, -and then a variable ``sq_root`` for storing the square root in each -cycle of the ``for`` loop. The variable names can be chosen by you. - -{{{ show the script which was created }}} - -Note that three lines after ``for`` statement, are indented using four -spaces. - -{{{ highlight the threee lines after for statement }}} - -It means that those three lines are part of the for loop. And it is -called a block of statements. And the seventh line or the immediate -line after the third line in the ``for`` loop is not indented, - -{{{ highlight the seventh line - the line just after for loop }}} - -it means that it is not part of the ``for`` loop and the lines after -that doesn't fall in the scope of the ``for`` loop. Thus each block is -separated by the indentation level. Thus marking the importance of -white-spaces in Python. - -{{{ switch to the slide which shows the problem statement of the first -problem to be tried out }}} - -Now a question for you to try, from the given numbers make a list of -perfect squares and a list of those which are not. The numbers are, -:: - - 7225, 3268, 3364, 2966, 7056, 5625, 729, 5547, 7056, 576, 2916 - -{{{ switch to next slide, problem statement of second problem in -solved exercie}}} - -Now let us try a simple one, to print the square root of numbers in -the list. And this time let us do it right in the IPython -interpreter. - -{{{ switch focus to the IPython interpreter }}} - -So let us start with making a list. Type the following -:: - - numbers = [1369, 7225, 3364, 7056, 5625, 729, 7056, 576, 2916] - for each in numbers: - -and now you will notice that, as soon as you press the return key -after for statement, the prompt changes to four dots and the cursor is -not right after the four dots but there are four spaces from the -dots. The four dots tell you that you are inside a block. Now type the -rest of the ``for`` loop, -:: - - sq_root = sqrt(each) - print "Square root of", each, "is", sq_root - -Now we have finished the statements in the block, and still the -interpreter is showing four dots, which means you are still inside the -block. To exit from the block press return key or the enter key twice -without entering anything else. It printed the square root of each -number in the list, and that is executed in a ``for`` loop. - -Now, let us generate the multiplication table of 10 from one to -ten. But this time let us try it in the vanilla version of Python -interpreter. - -Start the vanilla version of Python interpreter by issuing the command -``python`` in your terminal. - -{{{ open the python interpreter in the terminal using the command -python to start the vanilla Python interpreter }}} - -Start with, -:: - - for i in range(1,11): - -and press enter once, and we will see that this time it shows four -dots, but the cursor is close to the dots, so we have to intend the -block. So enter four spaces there and then type the following -:: - - - print "10 *",i,"=",i*10 - -Now when we hit enter, we still see the four dots, to get out of the -block type enter once. - -Okay! so the main thing here we learned is how to use Python -interpreter and IPython interpreter to specify blocks. But while we -were generating the multiplication table we used something new, -``range()`` function. ``range()`` is an inbuilt function in Python -which can be used to generate a ``list`` of integers from a starting -range to an ending range. Note that the ending number that you specify -will not be included in the ``list``. - -Now, let us print all the odd numbers from 1 to 50. Let us do it in -our IPython interpreter for ease of use. - -{{{ switch focus to ipython interpreter }}} - -{{{ switch to next slide, problem statement of the next problem in -solved exercises }}} - -Print the list of odd numbers from 1 to 50. It will be better if -you can try it out yourself. - -It is a very trivial problem and can be solved as, -:: - - print range(1,51,2) - -This time we passed three parameters to ``range()`` function unlike -the previous case where we passed only two parameters. The first two -parameters are the same in both the cases. The first parameter is the -starting number of the sequence and the second parameter is the end of -the range. Note that the sequence doesn't include the ending -number. The third parameter is for stepping through the sequence. Here -we gave two which means we are skipping every alternate element. - -{{{ switch to next slide, recap slide }}} - -Thus we come to the end of this tutorial. We learned about blocks in -Python, indentation, blocks in IPython, for loop, iterating over a -list and then the ``range()`` function. - -{{{ switch to next slide, thank you slide }}} - -Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: diff -r e675f9208b91 -r 4054b1a6392d input_output.rst --- a/input_output.rst Wed Oct 13 17:32:23 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 e675f9208b91 -r 4054b1a6392d input_output/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/input_output/questions.rst Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d input_output/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/input_output/quickref.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d input_output/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/input_output/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,208 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - + C - + D - + +.. #. How to print some value +.. #. How to print using modifiers +.. #. How to take input from user +.. #. How to display a prompt to the user before taking the input + + +.. Prerequisites +.. ------------- + +.. 1. Loops + +.. Author : Nishanth Amuluru + Internal Reviewer : + 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, y)`` + +{{{ continue from paused state }}} + +We see that the int value of x and float value of y are printed corresponding +to the modifiers used in the print statement. + +We can also see that print statement prints a new line character at the end of +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 }}} + +.. #[Puneeth: We didn't talk of new-line character till now, did we?] +.. #[Puneeth: non-programmers might not know?] + +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 e675f9208b91 -r 4054b1a6392d input_output/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/input_output/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,84 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: I/O +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Showing output to the user. + - Taking input from the user. +* Question 1 + What happens when you do ~print "x is %d y is %f" %(x, y)~ +* Solution 1 + ~int~ value of ~x~ and ~float~ value of ~y~ are printed corresponding to the + modifiers used in the ~print~ statement +* Question 2 + Enter the number 5.6 as input and store it in a variable called + ~c~. +* Solution 2 + #+begin_src python + In []: c = raw_input() + 5.6 + In []: c + #+end_src +* Question 3 + What happens when you do not enter anything and hit enter +* Solution 3 + #+begin_src python + In []: c = raw_input() + + In []: c + #+end_src +* Question 4 + How do you display a prompt and let the user enter input in a new line +* Solution 4 + #+begin_src python + In []: ip = raw_input("Please enter a number in the next line\n> ") + #+end_src +* Summary + You should now be able to -- + + Print a value "as is" + + Print a value using using modifiers + + Accept input from user + + Display a prompt before accepting input +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d input_output/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/input_output/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,144 @@ +% Created 2010-10-10 Sun 21:00 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{I/O} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Showing output to the user. +\item Taking input from the user. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + What happens when you do \texttt{print "x is \%d y is \%f" \%(x, y)} +\end{frame} +\begin{frame} +\frametitle{Solution 1} +\label{sec-3} + + \texttt{int} value of \texttt{x} and \texttt{float} value of \texttt{y} are printed corresponding to the + modifiers used in the \texttt{print} statement +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + Enter the number 5.6 as input and store it in a variable called + \texttt{c}. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} + +\lstset{language=Python} +\begin{lstlisting} +In []: c = raw_input() +5.6 +In []: c +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + + What happens when you do not enter anything and hit enter +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 3} +\label{sec-7} + +\lstset{language=Python} +\begin{lstlisting} +In []: c = raw_input() + +In []: c +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-8} + + How do you display a prompt and let the user enter input in a new line +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 4} +\label{sec-9} + +\lstset{language=Python} +\begin{lstlisting} +In []: ip = raw_input("Please enter a number in the next line\n> ") +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-10} + + You should now be able to -- +\begin{itemize} +\item Print a value ``as is'' +\item Print a value using using modifiers +\item Accept input from user +\item Display a prompt before accepting input +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-11} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d loading-data-from-files/pendulum.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading-data-from-files/pendulum.txt Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,90 @@ +1.0000e-01 6.9004e-01 +1.1000e-01 6.9497e-01 +1.2000e-01 7.4252e-01 +1.3000e-01 7.5360e-01 +1.4000e-01 8.3568e-01 +1.5000e-01 8.6789e-01 +1.6000e-01 8.4182e-01 +1.7000e-01 8.5379e-01 +1.8000e-01 8.5762e-01 +1.9000e-01 8.8390e-01 +2.0000e-01 8.9985e-01 +2.1000e-01 9.8436e-01 +2.2000e-01 1.0244e+00 +2.3000e-01 1.0572e+00 +2.4000e-01 9.9077e-01 +2.5000e-01 1.0058e+00 +2.6000e-01 1.0727e+00 +2.7000e-01 1.0943e+00 +2.8000e-01 1.1432e+00 +2.9000e-01 1.1045e+00 +3.0000e-01 1.1867e+00 +3.1000e-01 1.1385e+00 +3.2000e-01 1.2245e+00 +3.3000e-01 1.2406e+00 +3.4000e-01 1.2071e+00 +3.5000e-01 1.2658e+00 +3.6000e-01 1.2995e+00 +3.7000e-01 1.3142e+00 +3.8000e-01 1.2663e+00 +3.9000e-01 1.2578e+00 +4.0000e-01 1.2991e+00 +4.1000e-01 1.3058e+00 +4.2000e-01 1.3478e+00 +4.3000e-01 1.3506e+00 +4.4000e-01 1.4044e+00 +4.5000e-01 1.3948e+00 +4.6000e-01 1.3800e+00 +4.7000e-01 1.4480e+00 +4.8000e-01 1.4168e+00 +4.9000e-01 1.4719e+00 +5.0000e-01 1.4656e+00 +5.1000e-01 1.4399e+00 +5.2000e-01 1.5174e+00 +5.3000e-01 1.4988e+00 +5.4000e-01 1.4751e+00 +5.5000e-01 1.5326e+00 +5.6000e-01 1.5297e+00 +5.7000e-01 1.5372e+00 +5.8000e-01 1.6094e+00 +5.9000e-01 1.6352e+00 +6.0000e-01 1.5843e+00 +6.1000e-01 1.6643e+00 +6.2000e-01 1.5987e+00 +6.3000e-01 1.6585e+00 +6.4000e-01 1.6317e+00 +6.5000e-01 1.7074e+00 +6.6000e-01 1.6654e+00 +6.7000e-01 1.6551e+00 +6.8000e-01 1.6964e+00 +6.9000e-01 1.7143e+00 +7.0000e-01 1.7706e+00 +7.1000e-01 1.7622e+00 +7.2000e-01 1.7260e+00 +7.3000e-01 1.8089e+00 +7.4000e-01 1.7905e+00 +7.5000e-01 1.7428e+00 +7.6000e-01 1.8381e+00 +7.7000e-01 1.8182e+00 +7.8000e-01 1.7865e+00 +7.9000e-01 1.7995e+00 +8.0000e-01 1.8296e+00 +8.1000e-01 1.8625e+00 +8.2000e-01 1.8623e+00 +8.3000e-01 1.8383e+00 +8.4000e-01 1.8593e+00 +8.5000e-01 1.8944e+00 +8.6000e-01 1.9598e+00 +8.7000e-01 1.9000e+00 +8.8000e-01 1.9244e+00 +8.9000e-01 1.9397e+00 +9.0000e-01 1.9440e+00 +9.1000e-01 1.9718e+00 +9.2000e-01 1.9383e+00 +9.3000e-01 1.9555e+00 +9.4000e-01 2.0006e+00 +9.5000e-01 1.9841e+00 +9.6000e-01 2.0066e+00 +9.7000e-01 2.0493e+00 +9.8000e-01 2.0503e+00 +9.9000e-01 2.0214e+00 diff -r e675f9208b91 -r 4054b1a6392d loading-data-from-files/pendulum_semicolon.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading-data-from-files/pendulum_semicolon.txt Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,90 @@ +1.0000e-01;6.9004e-01 +1.1000e-01;6.9497e-01 +1.2000e-01;7.4252e-01 +1.3000e-01;7.5360e-01 +1.4000e-01;8.3568e-01 +1.5000e-01;8.6789e-01 +1.6000e-01;8.4182e-01 +1.7000e-01;8.5379e-01 +1.8000e-01;8.5762e-01 +1.9000e-01;8.8390e-01 +2.0000e-01;8.9985e-01 +2.1000e-01;9.8436e-01 +2.2000e-01;1.0244e+00 +2.3000e-01;1.0572e+00 +2.4000e-01;9.9077e-01 +2.5000e-01;1.0058e+00 +2.6000e-01;1.0727e+00 +2.7000e-01;1.0943e+00 +2.8000e-01;1.1432e+00 +2.9000e-01;1.1045e+00 +3.0000e-01;1.1867e+00 +3.1000e-01;1.1385e+00 +3.2000e-01;1.2245e+00 +3.3000e-01;1.2406e+00 +3.4000e-01;1.2071e+00 +3.5000e-01;1.2658e+00 +3.6000e-01;1.2995e+00 +3.7000e-01;1.3142e+00 +3.8000e-01;1.2663e+00 +3.9000e-01;1.2578e+00 +4.0000e-01;1.2991e+00 +4.1000e-01;1.3058e+00 +4.2000e-01;1.3478e+00 +4.3000e-01;1.3506e+00 +4.4000e-01;1.4044e+00 +4.5000e-01;1.3948e+00 +4.6000e-01;1.3800e+00 +4.7000e-01;1.4480e+00 +4.8000e-01;1.4168e+00 +4.9000e-01;1.4719e+00 +5.0000e-01;1.4656e+00 +5.1000e-01;1.4399e+00 +5.2000e-01;1.5174e+00 +5.3000e-01;1.4988e+00 +5.4000e-01;1.4751e+00 +5.5000e-01;1.5326e+00 +5.6000e-01;1.5297e+00 +5.7000e-01;1.5372e+00 +5.8000e-01;1.6094e+00 +5.9000e-01;1.6352e+00 +6.0000e-01;1.5843e+00 +6.1000e-01;1.6643e+00 +6.2000e-01;1.5987e+00 +6.3000e-01;1.6585e+00 +6.4000e-01;1.6317e+00 +6.5000e-01;1.7074e+00 +6.6000e-01;1.6654e+00 +6.7000e-01;1.6551e+00 +6.8000e-01;1.6964e+00 +6.9000e-01;1.7143e+00 +7.0000e-01;1.7706e+00 +7.1000e-01;1.7622e+00 +7.2000e-01;1.7260e+00 +7.3000e-01;1.8089e+00 +7.4000e-01;1.7905e+00 +7.5000e-01;1.7428e+00 +7.6000e-01;1.8381e+00 +7.7000e-01;1.8182e+00 +7.8000e-01;1.7865e+00 +7.9000e-01;1.7995e+00 +8.0000e-01;1.8296e+00 +8.1000e-01;1.8625e+00 +8.2000e-01;1.8623e+00 +8.3000e-01;1.8383e+00 +8.4000e-01;1.8593e+00 +8.5000e-01;1.8944e+00 +8.6000e-01;1.9598e+00 +8.7000e-01;1.9000e+00 +8.8000e-01;1.9244e+00 +8.9000e-01;1.9397e+00 +9.0000e-01;1.9440e+00 +9.1000e-01;1.9718e+00 +9.2000e-01;1.9383e+00 +9.3000e-01;1.9555e+00 +9.4000e-01;2.0006e+00 +9.5000e-01;1.9841e+00 +9.6000e-01;2.0066e+00 +9.7000e-01;2.0493e+00 +9.8000e-01;2.0503e+00 +9.9000e-01;2.0214e+00 diff -r e675f9208b91 -r 4054b1a6392d loading-data-from-files/primes.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading-data-from-files/primes.txt Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,25 @@ +2 +3 +5 +7 +11 +13 +17 +19 +23 +29 +31 +37 +41 +43 +47 +53 +59 +61 +67 +71 +73 +79 +83 +89 +97 diff -r e675f9208b91 -r 4054b1a6392d loading-data-from-files/questions.rst --- a/loading-data-from-files/questions.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/loading-data-from-files/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,17 +1,67 @@ -Objective ---------- +Objective Questions +------------------- .. A mininum of 8 questions here. -1. Question 1 -2. Question 2 -3. Question 3 +1. ``loadtxt`` can read data only from a file with one column + only. True or False? + + Answer: False + +#. To read a file with multiple columns, into separate simple + sequences, ``loadtxt`` is given the additional argument ______? + + Answer: ``unpack=True`` + +#. We have a file with two columns of data separated by one of the + following characters. Which of them doesn't require the delimiter + argument to be specified, when using ``loadtxt``. + + a. ; + #. , + #. : + #. [space] + + Answer: [space] + +#. Given a file ``data.txt`` with three columns of data separated by + spaces, read it into one complex sequence. + Answer: ``x = loadtxt("data.txt")`` -Programming ------------ +#. Given a file ``data.txt`` with three columns of data separated by + spaces, read it into 3 separate simple sequences. + + Answer: ``x = loadtxt("data.txt", unpack=True)`` + +#. Given a file ``data.txt`` with three columns of data separated by + ``:``, read it into one complex sequence. + + Answer: ``x = loadtxt("data.txt", delimiter=":")`` + +#. Given a file ``data.txt`` with three columns of data separated by + ":", read it into 3 separate simple sequences. + + Answer: ``x = loadtxt("data.txt", unpack=True, delimiter=":")`` + +#. To use the loadtxt command, each row should have the same number of + values, T or F ? + + Answer: True + +Larger Questions +---------------- .. A minimum of 2 questions here. -1. Programming Assignment 1 -2. Programming Assignment 2 +1. What will happen if one of the cells is empty? + +#. Given a file with 3 columns of data but two different delimiters, + what do you think will happen? + +#. Read a column with text? + +#. An input file contains 5 columns of data. Use only the second and fourth + columns of data and load into two different variables. + [hint: read the documentation, use the argument ``usecols``] + diff -r e675f9208b91 -r 4054b1a6392d loading-data-from-files/quickref.tex --- a/loading-data-from-files/quickref.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/loading-data-from-files/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,8 +1,12 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} +\textbf{Loading data from files} + +\lstinline|loadtxt('filename')| returns the columns of file in one +sequence. -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} +\lstinline|x, y = loadtxt('filename', unpack=True)| to obtain a file +with 2 columns in separate sequences. -Plotting two lists of equal length x, y:\\ -{\ex \lstinline| plot(x, y)|} +\lstinline|loadtxt('filename', delimiter=';')|, if the file has +columns separated by ';' instead of spaces/tabs. + + diff -r e675f9208b91 -r 4054b1a6392d loading-data-from-files/script.rst --- a/loading-data-from-files/script.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/loading-data-from-files/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,8 +1,30 @@ -======== - Script -======== +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. + Read data from files, containing a single column of data using the +.. ``loadtxt`` command. +.. + Read multiple columns of data, separated by spaces or other +.. delimiters. + + +.. Prerequisites +.. ------------- -Welcome to this tutorial on loading data from files. +.. 1. getting started with ``ipython`` + +.. Author : + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +{{{ Show the slide containing title }}} + +Hello Friends. Welcome to this tutorial on loading data from files. {{{ Screen shows welcome slide }}} @@ -59,15 +81,19 @@ Now, let us use the ``loadtxt`` command to read a file that contains two columns of data, ``pendulum.txt``. This file contains the length of the pendulum in the first column and the corresponding time period -in the second. +in the second. Note that ``loadtxt`` needs both the columns to have +equal number of rows. -%%1%% Pause the video here, and use the ``cat`` command to view the -contents of this file and then resume the video. +.. Following is an exercise that you must do. + +.. %%1%% Use the ``cat`` command to view the contents of this file. -This is how we look at the contents of the file, ``pendulum.txt`` -:: +.. Please, pause the video here. Do the exercise and then continue. - cat /home/fossee/pendulum.txt +.. This is how we look at the contents of the file, ``pendulum.txt`` +.. :: + +.. cat /home/fossee/pendulum.txt .. #[Nishanth]: The first column is L values and second is T values from a simle pelculum experiment. @@ -114,13 +140,14 @@ In this tutorial, we have learnt the basic use of the ``loadtxt`` command, which is capable of doing a lot more than we have used it for -until now, for example +until now. Let us look at an example, but before that do this +exercise. -%%2%% Pause the video here, and read the file -``pendulum_semicolon.txt`` which contains the same data as -``pendulum.txt``, but the columns are separated by semi-colons instead -of spaces. Use the IPython help to see how to do this. Once you have -finished, resume the video to look at the solution. +%%1%% Read the file ``pendulum_semicolon.txt`` which contains the same +data as ``pendulum.txt``, but the columns are separated by semi-colons +instead of spaces. Use the IPython help to see how to do this. + +Please, pause the video here. Do the exercise and then continue. {{{ switch back to the terminal }}} :: @@ -142,5 +169,10 @@ + Read multiple columns of data, separated by spaces or other delimiters. -Thank you! +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India +Hope you have enjoyed and found it useful. +Thank you! + diff -r e675f9208b91 -r 4054b1a6392d loading-data-from-files/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loading-data-from-files/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,67 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Loading data from files +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + + Read data from files with a single column of data + + Read data from files with multiple columns +* Question 1 + Read the file ~pendulum_semicolon.txt~ which contains the same data + as ~pendulum.txt~, but the columns are separated by semi-colons + instead of spaces. Use the IPython help to see how to do this. +* Solution 1 + #+begin_src python + In []: L, T = loadtxt('/home/fossee/pendulum_semicolon.txt', unpack=True, delimiter=';') + + In []: print L + + In []: print T + #+end_src +* Summary + + Read data from files, containing a single column of data using the + ~loadtxt~ command. + + Read multiple columns of data, separated by spaces or other + delimiters. +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d loading-data-from-files/slides.tex --- a/loading-data-from-files/slides.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/loading-data-from-files/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,95 +1,90 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{infolines} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} +% Created 2010-10-10 Sun 18:12 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{Loading data from files} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + \begin{frame} - \maketitle +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Read data from files with a single column of data +\item Read data from files with multiple columns +\end{itemize} \end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + Read the file \texttt{pendulum\_semicolon.txt} which contains the same data + as \texttt{pendulum.txt}, but the columns are separated by semi-colons + instead of spaces. Use the IPython help to see how to do this. +\end{frame} \begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} -\end{frame} +\frametitle{Solution 1} +\label{sec-3} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\lstset{language=Python} +\begin{lstlisting} +In []: L, T = loadtxt('/home/fossee/pendulum_semicolon.txt', unpack=True, delimiter=';') + +In []: print L -\begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} +In []: print T +\end{lstlisting} \end{frame} - \begin{frame} - \frametitle{Thank you!} +\frametitle{Summary} +\label{sec-4} + +\begin{itemize} +\item Read data from files, containing a single column of data using the + \texttt{loadtxt} command. +\item Read multiple columns of data, separated by spaces or other + delimiters. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-5} + \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r e675f9208b91 -r 4054b1a6392d loops/questions.rst --- a/loops/questions.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/loops/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,17 +1,93 @@ -Objective ---------- +Objective Questions +------------------- .. A mininum of 8 questions here. -1. Question 1 -2. Question 2 -3. Question 3 +1. Braces are used to indicate blocks in Python. True or False? + + Answer: False + +#. ``for`` can iterate over + + a. list of numbers + #. list of strings + #. strings + #. tuples + #. all of the above + +.. I was not sure of how to frame this question. Can someone fix it? + + Answer: all of the above + +#. ``x = range(20)``. What is x? + + Answer: A list of numbers from 0 to 19. + +#. ``x = range(5, 20)``. What is x? + Answer: A list of numbers from 5 to 19. + +#. ``x = range(0, 20, 5)``. What is x? + + a. [5, 10, 15, 20] + #. [0, 5, 10, 15, 20] + #. [0, 5, 10, 15] + #. Empty list + #. None of the Above + + Answer: [0, 5, 10, 15] + +#. ``x = range(20, 5)``. What is x? + + a. [5, 10, 15, 20] + #. [0, 5, 10, 15, 20] + #. [0, 5, 10, 15] + #. Empty list + #. None of the Above + + Answer: Empty list -Programming ------------ +#. ``x = range(20, 5, -1)``. What is x? + + Answer: A list of numbers from 20 to 6. + +#. What is the output of the following code block? + :: + + for i in range(1, 4): + for j in range(1, 4): + print i * j + break + + Answer: 1 to 3 is printed + +#. What is the output of the following code block? + :: + + for i in range(1, 4): + for j in range(1, 4): + pass + print i * j -.. A minimum of 2 questions here. + Answer:: + + 3 + 6 + 9 + +#. What is the output of the following code block? + :: -1. Programming Assignment 1 -2. Programming Assignment 2 + for i in range(1, 4): + for j in range(1, 4): + continue + print i * j + + Answer: Nothing is printed + +Larger Questions +---------------- + +1. A number is called Armstrong number if the sum of cubes of its digits is + equal to the number itself. Find all the three digit Armstrong numbers. + diff -r e675f9208b91 -r 4054b1a6392d loops/quickref.tex --- a/loops/quickref.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/loops/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,8 +1,16 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} +\textbf{loops} + +To iterate over a sequence: \lstinline|for i in sequence:|\\ +\texttt{i} is the looping variable. + +To iterate while a condition is true: \lstinline|while condition:| -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} +Blocks in python are indented. To end block return to the previous +indentation. + +To break out of the innermost loop: \lstinline|break| -Plotting two lists of equal length x, y:\\ -{\ex \lstinline| plot(x, y)|} +To skip to end of current iteration: \lstinline|continue| + +\lstinline|pass| is just a syntactic filler. + diff -r e675f9208b91 -r 4054b1a6392d loops/script.rst --- a/loops/script.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/loops/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,12 +1,34 @@ -======== - Script -======== +.. Objectives +.. ---------- + +.. By the end of this tutorial, you will be able to + +.. 1. use the ``for`` loop +.. #. use the ``while`` loop +.. #. Use ``break``, ``continue`` and ``pass`` statements to play around +.. with loops. + +.. Prerequisites +.. ------------- -{{{ show the welcome slide }}} +.. 1. getting started with ipython +.. #. getting started with for +.. #. conditionals -Welcome this tutorial on loops in Python. + +.. Author : + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] -{{{ show the outline slide }}} +Script +------ + +{{{ Show the slide containing title }}} + +Hello Friends. Welcome this tutorial on loops in Python. + +{{{ Show the outline slide }}} In this tutorial, we shall look at ``while`` and ``for`` loops. We shall then look at the ``break``, ``continue`` and ``pass`` keywords @@ -38,8 +60,12 @@ other block in Python, the code within the ``while`` block is indented to the right by 4 spaces. -E%% %% Pause the video here and write a ``while`` loop to print the -squares of all the even numbers below 10. Then, return to the video. +Following is an exercise that you must do. + +%%1%% Write a ``while`` loop to print the squares of all the even +numbers below 10. + +Please, pause the video here. Do the exercise and then continue. :: @@ -60,8 +86,12 @@ for n in range(1, 10, 2): print n*n -E%% %% Pause the video here and write a ``for`` loop to print the -squares of all the even numbers below 10. Then, return to the video. +Following is an exercise that you must do. + +%%2%% Write a ``for`` loop to print the squares of all the even +numbers below 10. + +Please, pause the video here. Do the exercise and then continue. :: @@ -106,10 +136,13 @@ print n*n -E%% %%Pause the video here and using the ``continue`` keyword modify -the ``for`` loop to print the squares of even numbers below 10, to -print the squares of only multiples of 4. (Do not modify the range -function call.) Then, resume the video. +Following is an exercise that you must do. + +%%3%%Using the ``continue`` keyword modify the ``for`` loop to print +the squares of even numbers below 10, to print the squares of only +multiples of 4. (Do not modify the range function call.) + +Please, pause the video here. Do the exercise and then continue. :: for n in range(2, 10, 2): @@ -117,8 +150,15 @@ continue print n*n +{{{ Show summary slide }}} + That brings us to the end of this tutorial. In this tutorial, we have learnt about looping structures in Python and the use of the keywords ``pass``, ``break`` and ``continue``. -Thank You! +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you! diff -r e675f9208b91 -r 4054b1a6392d loops/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/loops/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,87 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Loops +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Loop while a condition is true. + - Iterate over a sequence + - Breaking out of loops. + - Skipping iterations. +* Question 1 + Write a ~while~ loop to print the squares of all the even + numbers below 10. +* Solution 1 + #+begin_src python + In []: i = 2 + + In []: while i<10: + ....: print i*i + ....: i += 2 + #+end_src +* Question 2 + Write a ~for~ loop to print the squares of all the even numbers + below 10. +* Solution 2 + #+begin_src python + In []: for n in range(2, 10, 2): + ....: print n*n + #+end_src +* Question 3 + Using the ~continue~ keyword modify the ~for~ loop to print the + squares of even numbers below 10, to print the squares of only + multiples of 4. (Do not modify the range function call.) +* Solution 3 + #+begin_src python + for n in range(2, 10, 2): + if n%4: + continue + print n*n + #+end_src +* Summary + You should now be able to -- + - use the ~for~ loop + - use the ~while~ loop + - Use ~break~, ~continue~ and ~pass~ statements +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d loops/slides.tex --- a/loops/slides.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/loops/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,95 +1,128 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{infolines} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} +% Created 2010-10-10 Sun 21:15 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{Loops} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + \begin{frame} - \maketitle +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Loop while a condition is true. +\item Iterate over a sequence +\item Breaking out of loops. +\item Skipping iterations. +\end{itemize} \end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + Write a \texttt{while} loop to print the squares of all the even + numbers below 10. +\end{frame} \begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +In []: i = 2 + +In []: while i<10: + ....: print i*i + ....: i += 2 +\end{lstlisting} \end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + Write a \texttt{for} loop to print the squares of all the even numbers + below 10. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\lstset{language=Python} +\begin{lstlisting} +In []: for n in range(2, 10, 2): + ....: print n*n +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + Using the \texttt{continue} keyword modify the \texttt{for} loop to print the + squares of even numbers below 10, to print the squares of only + multiples of 4. (Do not modify the range function call.) +\end{frame} \begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 3} +\label{sec-7} + +\lstset{language=Python} +\begin{lstlisting} +for n in range(2, 10, 2): + if n%4: + continue + print n*n +\end{lstlisting} \end{frame} - \begin{frame} - \frametitle{Thank you!} +\frametitle{Summary} +\label{sec-8} + + You should now be able to -- +\begin{itemize} +\item use the \texttt{for} loop +\item use the \texttt{while} loop +\item Use \texttt{break}, \texttt{continue} and \texttt{pass} statements +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-9} + \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r e675f9208b91 -r 4054b1a6392d lstsq.rst --- a/lstsq.rst Wed Oct 13 17:32:23 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 e675f9208b91 -r 4054b1a6392d lstsq/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lstsq/questions.rst Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d lstsq/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lstsq/quickref.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d lstsq/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lstsq/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,141 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - + C - + D - + +.. Plotting a least square fit line + +.. 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 e675f9208b91 -r 4054b1a6392d lstsq/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lstsq/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,52 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Least square fit +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Plotting a Least square fit line +* Summary + You should now be able to -- + - Plot a least square fit line. +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d lstsq/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lstsq/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,77 @@ +% Created 2010-10-10 Sun 19:02 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Least square fit} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Plotting a Least square fit line +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-2} + + You should now be able to -- +\begin{itemize} +\item Plot a least square fit line. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-3} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d manipulating-lists.rst --- a/manipulating-lists.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,180 +0,0 @@ -Hello friends. Welcome to this spoken tutorial on Getting started with -strings. - -{{{ Show the slide containing the title }}} - -{{{ Show the slide containing the outline }}} - -We have already learnt a lot about Lists in Python. In this tutorial, -we will learn more about advanced features of Lists in Python. We will -see in detail how to concatenate two lists, slicing and striding of -lists, methods to sort and reverse the list. - -{{{ Shift to terminal and start ipython }}} - -To begin with let us start ipython, by typing:: - - ipython - -on the terminal - -We already know what Lists are in Python, how to access individual -elements in the list and some of the functions that can be run on the -lists like max, min, sum len and so on. Now let us learn some of the -basic operations that can be performed on Lists. - -We already know how to access individual elements in a List. But what -if we have a scenario where we need to get a part of the entire list -or what we call as a slice of the list? Python supports slicing on -lists. Let us say I have the list:: - - primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] - -To obtain the all the primes between 10 and 20 from the above list of -primes we say:: - - primes[4:8] - -This gives us all the elements in the list starting from the element -with the index 4 which is 11 in our list upto the element with index 8 -in the list but not including the eigth element. So we obtain a slice -starting from 11 upto 19th. It is a very important to remember that -when ever we specify a range of elements in Python the start index is -included and end index is not included. So in the above case, 11 which -was the element with the index 4 was included but 23 which was the -element with index 8 was exluded. - -Generalizing, we can obtain a slice of the list "p" from the index -"start" upto the index "end" but excluding "end" with the following -syntax - -{{{ Show the slide containing p[start:stop] }}} - -By default the slice fetches all the elements between start and stop -including start but not stop. So as to say we obtain all the elements -between start and stop in steps of one. Python also provides us the -functionality to specify the steps in which the slice must be -obtained. Say we have:: - - num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] - -If we want to obtain all the odd numbers less than 10 from the list -"num" we have to start from element with index 1 upto the index 10 in -steps of 2:: - - num[1:10:2] - -So if we don't specify the step it is by default 1. Similary there are -default values for start and stop indices as well. If we don't specify -the start index it is implicitly taken as the first element of the -list:: - - num[:10] - -This gives us all the elements from the beginning upto the 10th -element but not including the 10th element in the list "num". Similary -if the stop index is not specified it is implicitly assumed to be the -end of the list, including the last element of the list:: - - num[10:] - -gives all the elements starting from the 10th element in the list -"num" upto the final element including that last element. Now:: - - num[::2] - -gives us all the even numbers in the list "num". - -The other basic operation that we can perform on list is concatenation -of two or more lists. We can combine two lists by using the "plus" -operator. Say we have - -{{{ Read as you type }}}:: - - a = [1, 2, 3, 4] - b = [4, 5, 6, 7] - a + b - -When we concatenate lists using the "plus" operator we get a new -list. We can store this list in a new variable:: - - c = a + b - c - -It is important to observe that the "plus" operator always returns a -new list without touching anything in the existing lists which are the -operands of the concatenation operation. - -We know that list is a collection of data. Whenever we have a -collection we run into situations where we want to start the -collection. Lists support sort method which sorts the list inplace:: - - a = [5, 1, 6, 7, 7, 10] - a.sort() - -Now the contents of the list "a" will be:: - - a - [1, 5, 6, 7, 7, 10] - -Since the sort method sorts the list inplace the original list we had -is overwritten or replaced. We have no way to obtain the original list -back. One way to avoid this is to keep a copy of the original list in -another variable and run the sort method on the list. However Python -also provides a built-in function called sorted which sorts the list -which is passed as an argument to it and returns a new sorted list:: - - a = [5, 1, 6, 7, 7, 10] - sorted(a) - -We can store this sorted list another list variable:: - - sa = sorted(a) - -Similarly to perform certain operations on the list we would like to -reverse the list. Python provides reverse method which again reverses -the list inplace:: - - a = [1, 2, 3, 4, 5] - a.reverse() - -reverses the list "a" and stores the reversed list inplace i.e. in "a" -itself. Lets see the list "a":: - - a - [5, 4, 3, 2, 1] - -But again the original list is lost. If we want to obtain the reverse -of a list keeping the original list intact we can use the Python -built-in function reversed. reversed function returns a new list which -is the reverse of the list which was passed as the argument to the -reversed function:: - - a = [1, 2, 3, 4, 5] - reversed(a) - -We can also store this new reversed list in another list variable. - -{{{ Show summary slide }}} - -This brings us to the end of another session. In this tutorial session -we learnt - - * How to define strings - * Different types of defining a string - * String concatenation and repeatition - * Accessing individual elements of the string - * Immutability of strings - -{{{ Show the "sponsored by FOSSEE" slide }}} - -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thankyou - -.. Author : Madhu - Internal Reviewer 1 : [potential reviewer: Nishanth] - Internal Reviewer 2 : [potential reviewer: Amit] - External Reviewer : - diff -r e675f9208b91 -r 4054b1a6392d manipulating-lists/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-lists/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,72 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Given the list primes, ``primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, + 29]``, How do you obtain the last 4 primes? + + Answer: primes[-4:] + +#. Given the list primes, ``primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, + 29]``, What is the output of ``primes[::5]``? + + Answer: ``[2, 13]`` + +#. Given a list, p, of unknown length, obtain the first 3 (or all, if + there are fewer) characters of it. + + Answer: p[:3] + +#. The method ``reverse`` reverses a list in-place. True or False? + + Answer: True + +#. ``reversed`` function reverses a list in-place. True or False? + + Answer: False + +#. Given the list ``p = [1, 2, 3]``. p[4] produces an IndexError. True + or False? + + Answer: True + +#. Given the list ``p = [1, 2, 3]``. p[:4] produces an IndexError. True + or False? + + Answer: False + +#. Given the list primes, ``primes = [2, 3, 5, 7, 11]``, What is the + output of ``primes[::-1]``? + + Answer: [11, 7, 5, 3, 2] + +#. Given the list primes, ``primes = [2, 3, 5, 7, 11]``, What is the + output of ``primes[::-3]``? + + Answer: [11, 3] + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +#. Given a list p. Append it's reverse to itself. + + Answer:: + + p = p + reversed(p) + + +#. Marks is a list containing the roll numbers of students followed by + marks. [This is not a recommended way to hold the marks details, + but the teacher knows only so much Python!] Now she wants to get + the average of the marks. Help her do it. + + Answer:: + + marks = [1, 9, 2, 8, 3, 3, 4, 10, 5, 2] + average = sum(marks[1::2])/len(marks[1::2]) + + diff -r e675f9208b91 -r 4054b1a6392d manipulating-lists/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-lists/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,8 @@ +Creating a linear array:\\ +{\ex \lstinline| x = linspace(0, 2*pi, 50)|} + +Plotting two variables:\\ +{\ex \lstinline| plot(x, sin(x))|} + +Plotting two lists of equal length x, y:\\ +{\ex \lstinline| plot(x, y)|} diff -r e675f9208b91 -r 4054b1a6392d manipulating-lists/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-lists/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,196 @@ +.. Objectives +.. ---------- + +.. Clearly state the objectives of the LO (along with RBT level) + +.. Prerequisites +.. ------------- + +.. 1. getting started with lists +.. 2. +.. 3. + +.. Author : Madhu + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +{{{ Show the slide containing the title }}} + +Hello friends. Welcome to this spoken tutorial on Manipulating Lists. + + +{{{ Show the slide containing the outline }}} + +We have already learnt a lot about Lists in Python. In this tutorial, +we will learn more about advanced features of Lists in Python. We will +see in detail how to concatenate two lists, slicing and striding of +lists, methods to sort and reverse the list. + +{{{ Shift to terminal and start ipython }}} + +To begin with let us start ipython, by typing:: + + ipython + +on the terminal + +We already know what Lists are in Python, how to access individual +elements in the list and some of the functions that can be run on the +lists like max, min, sum len and so on. Now let us learn some of the +basic operations that can be performed on Lists. + +We already know how to access individual elements in a List. But what +if we have a scenario where we need to get a part of the entire list +or what we call as a slice of the list? Python supports slicing on +lists. Let us say I have the list:: + + primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + +To obtain the all the primes between 10 and 20 from the above list of +primes we say:: + + primes[4:8] + +This gives us all the elements in the list starting from the element +with the index 4 which is 11 in our list upto the element with index 8 +in the list but not including the eigth element. So we obtain a slice +starting from 11 upto 19th. It is a very important to remember that +when ever we specify a range of elements in Python the start index is +included and end index is not included. So in the above case, 11 which +was the element with the index 4 was included but 23 which was the +element with index 8 was excluded. + +Generalizing, we can obtain a slice of the list "p" from the index +"start" upto the index "end" but excluding "end" with the following +syntax + +{{{ Show the slide containing p[start:stop] }}} + +By default the slice fetches all the elements between start and stop +including start but not stop. So as to say we obtain all the elements +between start and stop in steps of one. Python also provides us the +functionality to specify the steps in which the slice must be +obtained. Say we have:: + + num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + +If we want to obtain all the odd numbers less than 10 from the list +"num" we have to start from element with index 1 upto the index 10 in +steps of 2:: + + num[1:10:2] + +So if we don't specify the step it is by default 1. Similary there are +default values for start and stop indices as well. If we don't specify +the start index it is implicitly taken as the first element of the +list:: + + num[:10] + +This gives us all the elements from the beginning upto the 10th +element but not including the 10th element in the list "num". Similary +if the stop index is not specified it is implicitly assumed to be the +end of the list, including the last element of the list:: + + num[10:] + +gives all the elements starting from the 10th element in the list +"num" upto the final element including that last element. Now:: + + num[::2] + +gives us all the even numbers in the list "num". + +The other basic operation that we can perform on list is concatenation +of two or more lists. We can combine two lists by using the "plus" +operator. Say we have + +{{{ Read as you type }}}:: + + a = [1, 2, 3, 4] + b = [4, 5, 6, 7] + a + b + +When we concatenate lists using the "plus" operator we get a new +list. We can store this list in a new variable:: + + c = a + b + c + +It is important to observe that the "plus" operator always returns a +new list without touching anything in the existing lists which are the +operands of the concatenation operation. + +We know that list is a collection of data. Whenever we have a +collection we run into situations where we want to start the +collection. Lists support sort method which sorts the list inplace:: + + a = [5, 1, 6, 7, 7, 10] + a.sort() + +Now the contents of the list "a" will be:: + + a + [1, 5, 6, 7, 7, 10] + +Since the sort method sorts the list inplace the original list we had +is overwritten or replaced. We have no way to obtain the original list +back. One way to avoid this is to keep a copy of the original list in +another variable and run the sort method on the list. However Python +also provides a built-in function called sorted which sorts the list +which is passed as an argument to it and returns a new sorted list:: + + a = [5, 1, 6, 7, 7, 10] + sorted(a) + +We can store this sorted list another list variable:: + + sa = sorted(a) + +Similarly to perform certain operations on the list we would like to +reverse the list. Python provides reverse method which again reverses +the list inplace:: + + a = [1, 2, 3, 4, 5] + a.reverse() + +reverses the list "a" and stores the reversed list inplace i.e. in "a" +itself. Lets see the list "a":: + + a + [5, 4, 3, 2, 1] + +But again the original list is lost. If we want to obtain the reverse +of a list keeping the original list intact we can use the Python +built-in function reversed. reversed function returns a new list which +is the reverse of the list which was passed as the argument to the +reversed function:: + + a = [1, 2, 3, 4, 5] + reversed(a) + +We can also store this new reversed list in another list variable. + +{{{ Show summary slide }}} + +This brings us to the end of another session. In this tutorial session +we learnt + + * How to define strings + * Different types of defining a string + * String concatenation and repeatition + * Accessing individual elements of the string + * Immutability of strings + +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you! + + diff -r e675f9208b91 -r 4054b1a6392d manipulating-lists/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-lists/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,123 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Accessing parts of arrays +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Manipulating one and multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slicing and striding on arrays to access chunks + - Read images into arrays and manipulations +* Sample Arrays + #+begin_src python + In []: A = array([12, 23, 34, 45, 56]) + + In []: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) + + #+end_src +* Question 1 + Change the last column of ~C~ to zeroes. +* Solution 1 + #+begin_src python + In []: C[:, -1] = 0 + #+end_src +* Question 2 + Change ~A~ to ~[11, 12, 13, 14, 15]~. +* Solution 2 + #+begin_src python + In []: A[:] = [11, 12, 13, 14, 15] + #+end_src +* squares.png + #+begin_latex + \begin{center} + \includegraphics[scale=0.6]{squares} + \end{center} + #+end_latex +* Question 3 + - obtain ~[22, 23]~ from ~C~. + - obtain ~[11, 21, 31, 41]~ from ~C~. + - obtain ~[21, 31, 41, 0]~. +* Solution 3 + #+begin_src python + In []: C[1, 1:3] + In []: C[0:4, 0] + In []: C[1:5, 0] + #+end_src +* Question 4 + Obtain ~[[23, 24], [33, -34]]~ from ~C~ +* Solution 4 + #+begin_src python + In []: C[1:3, 2:4] + #+end_src +* Question 5 + Obtain the square in the center of the image +* Solution 5 + #+begin_src python + In []: imshow(I[75:225, 75:225]) + #+end_src +* Question 6 + Obtain the following + #+begin_src python + [[12, 0], [42, 0]] + [[12, 13, 14], [0, 0, 0]] + #+end_src + +* Solution 6 + #+begin_src python + In []: C[::3, 1::3] + In []: C[::4, 1:4] + #+end_src +* Summary + You should now be able to -- + - Manipulate 1D \& Multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slice and stride on arrays + - Read images into arrays and manipulate them. +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d manipulating-lists/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-lists/slides.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d manipulating-strings/questions.rst --- a/manipulating-strings/questions.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/manipulating-strings/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,17 +1,94 @@ -Objective ---------- +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Given the list week:: + + ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] + + ``"Sun" in week`` returns True or False? + + Answer: False + +#. Given the string ``s = "palindrome"``, what is returned by s[4:] + + Answer: ``ndrome`` + +#. Given the string ``s = "palindrome"``, what is returned by s[-4] + + Answer: ``r`` + +#. Given the string ``s = "palindrome"``, what is returned by s[4::-1] -.. A mininum of 8 questions here. + Answer: ``nilap`` + +#. Given the string ``s = "palindrome"``, what is returned by s[-4:] + + Answer: ``rome`` + +#. Given a string ``s = "this is a string"``, how will you change it + to ``"this isn't a list"`` ? -1. Question 1 -2. Question 2 -3. Question 3 + Answer:: + + s = s.replace("string", "list") + s = s.replace("is", "isn't") + +#. Given a string ``s = "this is a string"``, how will you change it + to ``"THIS ISN'T A LIST"`` ? + + Answer:: + + s = s.replace("string", "list") + s = s.replace("is", "isn't") + s = s.upper() +#. Given a line from a CSV file (comma separated values), convert it + to a space separated line. -Programming ------------ + Answer: line.replace(',', ' ') + +#. Given the string "F.R.I.E.N.D.S" in s, obtain the "friends". + + Answer: ``s[::2].lower()`` + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Given the string friends, obtain the string "F.R.I.E.N.D.S". + + Answer:: + + s = "friends" + s = s.upper() + s_list = list(s) + ".".join(s_list) -.. A minimum of 2 questions here. +2. Given a string with double quotes and single quotes. Interchange + all the double quotes to single quotes and vice-versa. [Solve it + for this particular string. Not a generic one. Solve it for a + generic string, if you know how to iterate over a list.] + + s = """ "Isn't this a 'simple' task?" "No, it isn't." "Yes! it is." """ + + Answer:: + + s = s.replace('"', '#') + s = s.replace("'", '"') + s = s.replace('#', "'") -1. Programming Assignment 1 -2. Programming Assignment 2 + .. depends on ``for`` which is not an LO dependency a generic string. + + For generic string + Answer:: + + S = [] + s_list = s.split("'") + + for s_s in s_list: + S.append(s_s.replace('"', "'")) + + s = '"'.join(S) diff -r e675f9208b91 -r 4054b1a6392d manipulating-strings/quickref.tex --- a/manipulating-strings/quickref.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/manipulating-strings/quickref.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,8 +1,14 @@ -Creating a linear array:\\ -{\ex \lstinline| x = linspace(0, 2*pi, 50)|} +\textbf{Manipulating strings} + +String indexing starts from 0, like lists. -Plotting two variables:\\ -{\ex \lstinline| plot(x, sin(x))|} +\lstinline|s = `Hello World'|\\ +\lstinline|s[0:5]| gives \texttt{Hello}\\ +\lstinline|s[6:]| gives \textt{World}\\ +\lstinline|s[6::2]| gives \textt{Wrd}\\ -Plotting two lists of equal length x, y:\\ -{\ex \lstinline| plot(x, y)|} +\lstinline|s.replace('e', 'a')| returns a new string with all e's +replaced by a. + +\lstinline|s.lower()| and \lstinline|s.upper()| return new strings +with all lower and upper case letters, respectively. diff -r e675f9208b91 -r 4054b1a6392d manipulating-strings/script.rst --- a/manipulating-strings/script.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/manipulating-strings/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,18 +1,40 @@ -======== - Script -======== +.. Objectives +.. ---------- + +.. By the end of this tutorial, you will be able to + +.. 1. Slice strings and get sub-strings out of them +.. #. Reverse strings +.. #. Replace characters in strings. +.. #. Convert strings to upper or lower case +.. #. joining a list of strings + +.. Prerequisites +.. ------------- -{{{ show the welcome slide }}} +.. 1. getting started with strings +.. #. getting started with lists +.. #. basic datatypes + +.. Author : Puneeth + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] -Welcome to this tutorial on manipulating strings. +Script +------ + +{{{ Show the slide containing title }}} + +Hello Friends. Welcome to this tutorial on manipulating strings. {{{ show the slide with outline }}} In this tutorial we shall learn to manipulate strings, specifically slicing and reversing them, or replacing characters, converting from -upper to lower case and vice-versa +upper to lower case and vice-versa and joining a list of strings. -#[punch: reversed returns an iterator. should we still teach it?] +.. #[punch: reversed returns an iterator. should we still teach it?] We have an ``ipython`` shell open, in which we are going to work, through out this session. @@ -59,8 +81,12 @@ As we already know, the last element of the string can be accessed using ``s[-1]``. -%%1%% Pause the video here and obtain the sub-string excluding the -first and last characters from the string. +Following is an exercise that you must do. + +%%1%% Obtain the sub-string excluding the first and last characters +from the string s. + +Please, pause the video here. Do the exercise(s) and then continue. :: @@ -131,13 +157,18 @@ Note that these methods, do not change the original string, but return a new string. -a%% %% Pause the video here, and finish the problem of checking if -``s`` is a valid name of a day of the week and then resume the -video. Change the solution to this problem, to include forms like, -SAT, SATURDAY, Saturday and Sat. +Following is an exercise that you must do. + +%%2%% Check if ``s`` is a valid name of a day of the week. Change the +solution to this problem, to include forms like, SAT, SATURDAY, +Saturday and Sat. + +Please, pause the video here. Do the exercise and then continue. :: + s in week + s.lower()[:3] in week We just convert any input string to lower case and then check if it is @@ -160,20 +191,59 @@ email = email.replace("[at]", "@") print email -%%1%% Pause the video here and replace the ``[dot]`` with ``.`` and then -resume the video. +Following is an exercise that you must do. + +%%3%% Replace the ``[dot]`` with ``.`` in ``email`` + +Please, pause the video here. Do the exercise and then continue. :: email = email.replace("[dot]", ".") print email +Now, let's look at another interesting problem where we have a list of +e-mail addresses and we wish to obtain one long string of e-mail +addresses separated by commas or semi-colons. + +:: + + email_list = ["info@fossee.in", "enquiries@fossee.in", "help@fossee.in"] + + +Now, if we wish to obtain one long string, separating each of the +email id by a comma, we use the join operator on ``,``. + +:: + + email_str = ", ".join(email_list) + print email_str + +Notice that the email ids are joined by a comma followed by a space. + +Following is an exercise that you must do. + +%%3%% From the email_str that we generated, change the separator to be +a semicolon instead of a comma. + +Please, pause the video here. Do the exercise and then continue. + +:: + + email_str = email_str.replace(",", ";") That brings us to the end of the tutorial. {{{ show summary slide }}} In this tutorial, we have learnt how to get substrings, reverse -strings and a few useful methods, namely upper, lower and replace. +strings and a few useful methods, namely upper, lower, replace and +join. + +{{{ Show the "sponsored by FOSSEE" slide }}} -Thank You! +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you! + diff -r e675f9208b91 -r 4054b1a6392d manipulating-strings/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/manipulating-strings/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,94 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Manipulating strings +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Slicing strings to get sub-strings + - Reversing strings + - Replacing characters in strings. + - Converting strings to upper or lower case + - Joining a list of strings +* Question 1 + Obtain the sub-string excluding the first and last characters from + the string ~s~. +* Solution 1 + #+begin_src python + In []: s[1:-1] + #+end_src +* Question 2 + Given a list week, week = ~week = ["sun", "mon", "tue", "wed", + "thu", "fri", "sat"]~. Check if ~s~ is a valid name of a day of the + week. Change the solution to this problem, to include forms like, + SAT, SATURDAY, Saturday and Sat. +* Solution 2 + #+begin_src python + In []: s in week + In []: s.lower()[:3] in week + #+end_src +* Question 3 + Given ~email~ -- ~info@fossee[dot]in~ + + Replace the ~[dot]~ with ~.~ in ~email~ +* Solution 3 + #+begin_src python + email.replace('[dot], '.') + print email + #+end_src +* Question 4 + From the ~email_str~ that we generated, change the separator to be a + semicolon instead of a comma. +* Solution 4 + #+begin_src python + email_str = email_str.replace(",", ";") + #+end_src +* Summary + You should now be able to -- + - Slice strings and get sub-strings out of them + - Reverse strings + - Replace characters in strings. + - Convert strings to upper or lower case + - Join a list of strings + +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d manipulating-strings/slides.tex --- a/manipulating-strings/slides.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/manipulating-strings/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,95 +1,142 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{infolines} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} +% Created 2010-10-11 Mon 11:27 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{Manipulating strings} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + \begin{frame} - \maketitle +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Slicing strings to get sub-strings +\item Reversing strings +\item Replacing characters in strings. +\item Converting strings to upper or lower case +\item Joining a list of strings +\end{itemize} \end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + Obtain the sub-string excluding the first and last characters from + the string \texttt{s}. +\end{frame} \begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +In []: s[1:-1] +\end{lstlisting} \end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + Given a list week, week = \texttt{week = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]}. Check if \texttt{s} is a valid name of a day of the + week. Change the solution to this problem, to include forms like, + SAT, SATURDAY, Saturday and Sat. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\lstset{language=Python} +\begin{lstlisting} +In []: s in week +In []: s.lower()[:3] in week +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + Given \texttt{email} -- \texttt{info@fossee[dot]in} + + Replace the \texttt{[dot]} with \texttt{.} in \texttt{email} +\end{frame} \begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} +\frametitle{Solution 3} +\label{sec-7} + +\lstset{language=Python} +\begin{lstlisting} +email.replace('[dot], '.') +print email +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 4} +\label{sec-8} + + From the \texttt{email\_str} that we generated, change the separator to be a + semicolon instead of a comma. \end{frame} +\begin{frame}[fragile] +\frametitle{Solution 4} +\label{sec-9} +\lstset{language=Python} +\begin{lstlisting} +email_str = email_str.replace(",", ";") +\end{lstlisting} +\end{frame} \begin{frame} - \frametitle{Thank you!} +\frametitle{Summary} +\label{sec-10} + + You should now be able to -- +\begin{itemize} +\item Slice strings and get sub-strings out of them +\item Reverse strings +\item Replace characters in strings. +\item Convert strings to upper or lower case +\item Join a list of strings +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-11} + \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r e675f9208b91 -r 4054b1a6392d matrices/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/matrices/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,116 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. ``matrix(A) * matrix(B)`` and ``array(A) * array(B)`` are the same. + + a. True + #. False + +Answer: False + +2. ``matrix(A) * array(B)`` does, + + a. Element wise multiplication. + #. Matrix multiplication. + #. Cannot multiply a matrix object and array object. + #. Depends on the shape of A and B, if compatible matrix + multiplication will be done, otherwise element wise + multiplication. + +Answer: Matrix multiplication + +3. A and B are two matrix objects. Element wise multiplication in + matrices are done by, + + a. A * B + #. ``multiply(A, B)`` + #. ``dot(A, B)`` + #. ``element_multiply(A,B)`` + +Answer: multiply(A, B) + +4. ``norm(A)`` method determines the, + + a. Frobenius norm + #. Infinity norm + #. Induced norm + #. Schatten norm + +Answer: Frobenius norm + +5. ``eig(A)[1]`` and ``eigvals(A)`` are the same. + + a. True + #. False + +Answer: False + +6. The code snippet will work without an error, + :: + + A = matrix([[1, 2, 3, 4], [5, 6, 7, 8]]) + inv(A) + + a. True + #. False + +Answer: False + +7. What is the output of the following code, + :: + + x = matrix([[1, 2, 3], ['a', 2, 'c']]) + identity(x.shape) + + a. Will create an identity matrix of shape (2, 3). + #. ``identity()`` function takes an integer as argument and a tuple + is passed. + #. Will return, matrix([[1,0,1],[0,1,0]]) + #. Will return, matrix([[0,1,0],[0,1,0]]) + +Answer: ``identity()`` function takes an integer as argument and a + tuple is passed. + +8. ``norm(A,ord='fro')`` is the same as ``norm(A)`` + + a. True + #. False + +Answer: True + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Consider an array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. A fold and add + operation consist of two phases, a right fold and add and a left + fold and add. + + Say in first fold and add, we take the right fold of the array and + add it to the left like, + + [1+10, 2+9, 3+8, 4+7, 5+6, 6, 7, 8, 9, 10] + + and it becomes + + [11, 11, 11, 11, 11, 6, 7, 8, 9, 10] + + and in the second fold and add, we take the left fold of the new + array and add it to the right and it becomes, + + [11, 11, 11, 11, 11, 17, 18, 19, 20, 21]. + + What will be the array after 22 such operations starting with [1, + 2, 3, 4, 5, 6, 7, 8, 9, 10] + +2. Find the infinity norm and the determinant of the inverse of the + product of matrices A and B. + :: + + A = [[ 1, 2, 3, 4], B = [[16, 15, 14, 13], + [ 5, 6, 7, 8], [12, 11, 10, 9], + [ 9, 10, 11, 12], [ 8, 7, 6, 5], + [13, 14, 15, 16]] [ 4, 3, 2, 1]] diff -r e675f9208b91 -r 4054b1a6392d matrices/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/matrices/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,293 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Create matrices using data. +.. #. Create matrices from lists. +.. #. Basic matrix operations. +.. #. Use ``inv()`` function to find inverse of a matrix. +.. #. Use ``det()`` function to find determinant of a matrix. +.. #. Use ``eig()`` and ``eigvals()`` functions to find eigen values + and vectors +.. #. Use ``norm()`` function to find norm of a matrix. +.. #. Use ``svd()`` function to find singular value decomposition of a + matrix. + + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` and ``pylab`` installed. +.. #. getting started with ``ipython``. +.. #. getting started with lists. +.. #. getting started with arrays. +.. #. accessing part of arrays. + + +.. Author : Anoop Jacob Thomas + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + + +======== +Matrices +======== +{{{ show the welcome slide }}} + +Welcome to the spoken tutorial on Matrices. + +{{{ switch to next slide, outline slide }}} + +In this tutorial we will learn about matrices, creating matrices using +direct data, by converting a list, matrix operations. Finding inverse +of a matrix, determinant of a matrix, eigen values and eigen vectors +of a matrix, norm and singular value decomposition of matrices. + +{{{ creating a matrix }}} + +All matrix operations are done using arrays. Thus all the operations +on arrays are valid on matrices also. A matrix may be created as, +:: + + m1 = matrix([1,2,3,4]) + +Using the tuple ``m1.shape`` we can find out the shape or size of the +matrix, +:: + + m1.shape + +Since it is a one row four column matrix it returned a tuple, one by +four. + +A list can be converted to a matrix as follows, +:: + + l1 = [[1,2,3,4],[5,6,7,8]] + m2 = matrix(l1) + +Note that all matrix operations are done using arrays, so a matrix may +also be created as +:: + + m3 = array([[5,6,7,8],[9,10,11,12]]) + +{{{ switch to next slide, matrix operations }}} + +We can do matrix addition and subtraction as, +:: + + m3 + m2 + +does element by element addition, thus matrix addition. + +Similarly, +:: + + m3 - m2 + +it does matrix subtraction, that is element by element +subtraction. Now let us try, + +{{{ Switch to next slide, Matrix multiplication }}} +:: + + m3 * m2 + +Note that in arrays ``array(A) star array(B)`` does element wise +multiplication and not matrix multiplication, but unlike arrays, the +operation ``matrix(A) star matrix(B)`` does matrix multiplication and +not element wise multiplication. And in this case since the sizes are +not compatible for multiplication it returned an error. + +And element wise multiplication in matrices are done using the +function ``multiply()`` +:: + + multiply(m3,m2) + +{{{ switch to next slide, Matrix multiplication (cont'd) }}} + +Now let us see an example for matrix multiplication. For doing matrix +multiplication we need to have two matrices of the order n by m and m +by r and the resulting matrix will be of the order n by r. Thus let us +first create two matrices which are compatible for multiplication. +:: + + m1.shape + +matrix m1 is of the shape one by four, let us create another one of +the order four by two, +:: + + m4 = matrix([[1,2],[3,4],[5,6],[7,8]]) + m1 * m4 + +thus unlike in array object ``star`` can be used for matrix multiplication +in matrix object. + +{{{ switch to next slide, recall from arrays }}} + +As we already saw in arrays, the functions ``identity()`` which +creates an identity matrix of the order n by n, ``zeros()`` which +creates a matrix of the order m by n with all zeros, ``zeros_like()`` +which creates a matrix with zeros with the shape of the matrix passed, +``ones()`` which creates a matrix of order m by n with all ones, +``ones_like()`` which creates a matrix with ones with the shape of the +matrix passed. These functions can also be used with matrices. + +{{{ switch to next slide, more matrix operations }}} + +To find out the transpose of a matrix we can do, +:: + + print m4 + m4.T + +Matrix name dot capital T will give the transpose of a matrix + +{{{ switch to next slide, Frobenius norm of inverse of matrix }}} + +Now let us try to find out the Frobenius norm of inverse of a 4 by 4 +matrix, the matrix being, +:: + + m5 = matrix(arange(1,17).reshape(4,4)) + print m5 + +The inverse of a matrix A, A raise to minus one is also called the +reciprocal matrix such that A multiplied by A inverse will give 1. The +Frobenius norm of a matrix is defined as square root of sum of squares +of elements in the matrix. Pause here and try to solve the problem +yourself, the inverse of a matrix can be found using the function +``inv(A)``. + +And here is the solution, first let us find the inverse of matrix m5. +:: + + im5 = inv(m5) + +And the Frobenius norm of the matrix ``im5`` can be found out as, +:: + + sum = 0 + for each in array(im5.flatten())[0]: + sum += each * each + print sqrt(sum) + +{{{ switch to next slide, infinity norm }}} + +Now try to find out the infinity norm of the matrix im5. The infinity +norm of a matrix is defined as the maximum value of sum of the +absolute of elements in each row. Pause here and try to solve the +problem yourself. + +The solution for the problem is, +:: + + sum_rows = [] + for i in im5: + sum_rows.append(abs(i).sum()) + print max(sum_rows) + +{{{ switch to slide the ``norm()`` method }}} + +Well! to find the Frobenius norm and Infinity norm we have an even easier +method, and let us see that now. + +The norm of a matrix can be found out using the method +``norm()``. Inorder to find out the Frobenius norm of the matrix im5, +we do, +:: + + norm(im5) + +And to find out the Infinity norm of the matrix im5, we do, +:: + + norm(im5,ord=inf) + +This is easier when compared to the code we wrote. Do ``norm`` +question mark to read up more about ord and the possible type of norms +the norm function produces. + +{{{ switch to next slide, determinant }}} + +Now let us find out the determinant of a the matrix m5. + +The determinant of a square matrix can be obtained using the function +``det()`` and the determinant of m5 can be found out as, +:: + + det(m5) + +{{{ switch to next slide, eigen vectors and eigen values }}} + +The eigen values and eigen vector of a square matrix can be computed +using the function ``eig()`` and ``eigvals()``. + +Let us find out the eigen values and eigen vectors of the matrix +m5. We can do it as, +:: + + eig(m5) + +Note that it returned a tuple of two matrices. The first element in +the tuple are the eigen values and the second element in the tuple are +the eigen vectors. Thus the eigen values are, +:: + + eig(m5)[0] + +and the eigen vectors are, +:: + + eig(m5)[1] + +The eigen values can also be computed using the function ``eigvals()`` as, +:: + + eigvals(m5) + +{{{ switch to next slide, singular value decomposition }}} + +Now let us learn how to do the singular value decomposition or S V D +of a matrix. + +Suppose M is an m×n matrix whose entries come from the field K, which +is either the field of real numbers or the field of complex +numbers. Then there exists a factorization of the form + + M = U\Sigma V star + +where U is an (m by m) unitary matrix over K, the matrix \Sigma is an +(m by n) diagonal matrix with nonnegative real numbers on the +diagonal, and V*, an (n by n) unitary matrix over K, denotes the +conjugate transpose of V. Such a factorization is called the +singular-value decomposition of M. + +The SVD of matrix m5 can be found as +:: + + svd(m5) + +Notice that it returned a tuple of 3 elements. The first one U the +next one Sigma and the third one V star. + +{{{ switch to next slide, recap slide }}} + +So this brings us to the end of this tutorial. In this tutorial, we +learned about matrices, creating matrices, matrix operations, inverse +of matrices, determinant, norm, eigen values and vectors and singular +value decomposition of matrices. + +{{{ switch to next slide, thank you }}} + +Thank you! + +.. Author: Anoop Jacob Thomas + Reviewer 1: + Reviewer 2: + External reviewer: diff -r e675f9208b91 -r 4054b1a6392d matrices/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/matrices/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,176 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Matrices +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Creating Matrices + - using direct data + - converting a list + - Matrix operations + - Inverse of matrix + - Determinant of matrix + - Eigen values and Eigen vectors of matrices + - Norm of matrix + - Singular Value Decomposition of matrices + +* Creating a matrix + - Creating a matrix using direct data + : In []: m1 = matrix([1, 2, 3, 4]) + - Creating a matrix using lists + : In []: l1 = [[1,2,3,4],[5,6,7,8]] + : In []: m2 = matrix(l1) + - A matrix is basically an array + : In []: m3 = array([[5,6,7,8],[9,10,11,12]]) + +* Matrix operations + - Element-wise addition (both matrix should be of order ~mXn~) + : In []: m3 + m2 + - Element-wise subtraction (both matrix should be of order ~mXn~) + : In []: m3 - m2 +* Matrix Multiplication + - Matrix Multiplication + : In []: m3 * m2 + : Out []: ValueError: objects are not aligned + - Element-wise multiplication using ~multiply()~ + : multiply(m3, m2) + +* Matrix Multiplication (cont'd) + - Create two compatible matrices of order ~nXm~ and ~mXr~ + : In []: m1.shape + - matrix m1 is of order ~1 X 4~ + - Creating another matrix of order ~4 X 2~ + : In []: m4 = matrix([[1,2],[3,4],[5,6],[7,8]]) + - Matrix multiplication + : In []: m1 * m4 +* Recall from ~array~ + - The functions + - ~identity(n)~ - + creates an identity matrix of order ~nXn~ + - ~zeros((m,n))~ - + creates a matrix of order ~mXn~ with 0's + - ~zeros_like(A)~ - + creates a matrix with 0's similar to the shape of matrix ~A~ + - ~ones((m,n))~ + creates a matrix of order ~mXn~ with 1's + - ~ones_like(A)~ + creates a matrix with 1's similar to the shape of matrix ~A~ + Can also be used with matrices + +* More matrix operations + Transpose of a matrix + : In []: m4.T +* Exercise 1 : Frobenius norm \& inverse + Find out the Frobenius norm of inverse of a ~4 X 4~ matrix. + : + The matrix is + : m5 = matrix(arange(1,17).reshape(4,4)) + - Inverse of A, + - + #+begin_latex + $A^{-1} = inv(A)$ + #+end_latex + - Frobenius norm is defined as, + - + #+begin_latex + $||A||_F = [\sum_{i,j} abs(a_{i,j})^2]^{1/2}$ + #+end_latex + +* Exercise 2: Infinity norm + Find the infinity norm of the matrix ~im5~ + : + - Infinity norm is defined as, + #+begin_latex + $max([\sum_{i} abs(a_{i})^2])$ + #+end_latex +* ~norm()~ method + - Frobenius norm + : In []: norm(im5) + - Infinity norm + : In []: norm(im5, ord=inf) +* Determinant + Find out the determinant of the matrix m5 + : + - determinant can be found out using + - ~det(A)~ - returns the determinant of matrix ~A~ +* eigen values \& eigen vectors + Find out the eigen values and eigen vectors of the matrix ~m5~. + : + - eigen values and vectors can be found out using + : In []: eig(m5) + returns a tuple of /eigen values/ and /eigen vectors/ + - /eigen values/ in tuple + - ~In []: eig(m5)[0]~ + - /eigen vectors/ in tuple + - ~In []: eig(m5)[1]~ + - Computing /eigen values/ using ~eigvals()~ + : In []: eigvals(m5) +* Singular Value Decomposition (~svd~) + #+begin_latex + $M = U \Sigma V^*$ + #+end_latex + - U, an ~mXm~ unitary matrix over K. + - + #+begin_latex + $\Sigma$ + #+end_latex + , an ~mXn~ diagonal matrix with non-negative real numbers on diagonal. + - + #+begin_latex + $V^*$ + #+end_latex + , an ~nXn~ unitary matrix over K, denotes the conjugate transpose of V. + - SVD of matrix ~m5~ can be found out as, + : In []: svd(m5) +* Summary + - Matrices + - creating matrices + - Matrix operations + - Inverse (~inv()~) + - Determinant (~det()~) + - Norm (~norm()~) + - Eigen values \& vectors (~eig(), eigvals()~) + - Singular Value Decomposition (~svd()~) + +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d matrices/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/matrices/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,357 @@ +% Created 2010-10-12 Tue 14:28 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Matrices} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Creating Matrices + +\begin{itemize} +\item using direct data +\item converting a list +\end{itemize} + +\item Matrix operations +\item Inverse of matrix +\item Determinant of matrix +\item Eigen values and Eigen vectors of matrices +\item Norm of matrix +\item Singular Value Decomposition of matrices +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Creating a matrix} +\label{sec-2} + +\begin{itemize} +\item Creating a matrix using direct data +\end{itemize} + +\begin{verbatim} + In []: m1 = matrix([1, 2, 3, 4]) +\end{verbatim} + +\begin{itemize} +\item Creating a matrix using lists +\end{itemize} + +\begin{verbatim} + In []: l1 = [[1,2,3,4],[5,6,7,8]] + In []: m2 = matrix(l1) +\end{verbatim} + +\begin{itemize} +\item A matrix is basically an array +\end{itemize} + +\begin{verbatim} + In []: m3 = array([[5,6,7,8],[9,10,11,12]]) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Matrix operations} +\label{sec-3} + +\begin{itemize} +\item Element-wise addition (both matrix should be of order \texttt{mXn}) +\begin{verbatim} + In []: m3 + m2 +\end{verbatim} + +\item Element-wise subtraction (both matrix should be of order \texttt{mXn}) +\begin{verbatim} + In []: m3 - m2 +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Matrix Multiplication} +\label{sec-4} + +\begin{itemize} +\item Matrix Multiplication +\begin{verbatim} + In []: m3 * m2 + Out []: ValueError: objects are not aligned +\end{verbatim} + +\item Element-wise multiplication using \texttt{multiply()} +\begin{verbatim} + multiply(m3, m2) +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Matrix Multiplication (cont'd)} +\label{sec-5} + +\begin{itemize} +\item Create two compatible matrices of order \texttt{nXm} and \texttt{mXr} +\begin{verbatim} + In []: m1.shape +\end{verbatim} + + +\begin{itemize} +\item matrix m1 is of order \texttt{1 X 4} +\end{itemize} + +\item Creating another matrix of order \texttt{4 X 2} +\begin{verbatim} + In []: m4 = matrix([[1,2],[3,4],[5,6],[7,8]]) +\end{verbatim} + +\item Matrix multiplication +\begin{verbatim} + In []: m1 * m4 +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Recall from \texttt{array}} +\label{sec-6} + +\begin{itemize} +\item The functions + +\begin{itemize} +\item \texttt{identity(n)} - + creates an identity matrix of order \texttt{nXn} +\item \texttt{zeros((m,n))} - + creates a matrix of order \texttt{mXn} with 0's +\item \texttt{zeros\_like(A)} - + creates a matrix with 0's similar to the shape of matrix \texttt{A} +\item \texttt{ones((m,n))} + creates a matrix of order \texttt{mXn} with 1's +\item \texttt{ones\_like(A)} + creates a matrix with 1's similar to the shape of matrix \texttt{A} +\end{itemize} + +\end{itemize} + + Can also be used with matrices +\end{frame} +\begin{frame}[fragile] +\frametitle{More matrix operations} +\label{sec-7} + + Transpose of a matrix +\begin{verbatim} + In []: m4.T +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 1 : Frobenius norm \& inverse} +\label{sec-8} + + Find out the Frobenius norm of inverse of a \texttt{4 X 4} matrix. +\begin{verbatim} + +\end{verbatim} + + The matrix is +\begin{verbatim} + m5 = matrix(arange(1,17).reshape(4,4)) +\end{verbatim} + +\begin{itemize} +\item Inverse of A, + +\begin{itemize} +\item $A^{-1} = inv(A)$ +\end{itemize} + +\item Frobenius norm is defined as, + +\begin{itemize} +\item $||A||_F = [\sum_{i,j} abs(a_{i,j})^2]^{1/2}$ +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 2: Infinity norm} +\label{sec-9} + + Find the infinity norm of the matrix \texttt{im5} +\begin{verbatim} + +\end{verbatim} + +\begin{itemize} +\item Infinity norm is defined as, + $max([\sum_{i} abs(a_{i})^2])$ +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{norm()} method} +\label{sec-10} + +\begin{itemize} +\item Frobenius norm +\begin{verbatim} + In []: norm(im5) +\end{verbatim} + +\item Infinity norm +\begin{verbatim} + In []: norm(im5, ord=inf) +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Determinant} +\label{sec-11} + + Find out the determinant of the matrix m5 +\begin{verbatim} + +\end{verbatim} + +\begin{itemize} +\item determinant can be found out using + +\begin{itemize} +\item \texttt{det(A)} - returns the determinant of matrix \texttt{A} +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{eigen values \& eigen vectors} +\label{sec-12} + + Find out the eigen values and eigen vectors of the matrix \texttt{m5}. +\begin{verbatim} + +\end{verbatim} + +\begin{itemize} +\item eigen values and vectors can be found out using +\begin{verbatim} + In []: eig(m5) +\end{verbatim} + + returns a tuple of \emph{eigen values} and \emph{eigen vectors} +\item \emph{eigen values} in tuple + +\begin{itemize} +\item \texttt{In []: eig(m5)[0]} +\end{itemize} + +\item \emph{eigen vectors} in tuple + +\begin{itemize} +\item \texttt{In []: eig(m5)[1]} +\end{itemize} + +\item Computing \emph{eigen values} using \texttt{eigvals()} +\begin{verbatim} + In []: eigvals(m5) +\end{verbatim} + +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Singular Value Decomposition (\texttt{svd})} +\label{sec-13} + + $M = U \Sigma V^*$ +\begin{itemize} +\item U, an \texttt{mXm} unitary matrix over K. +\item $\Sigma$ + , an \texttt{mXn} diagonal matrix with non-negative real numbers on diagonal. +\item $V^*$ + , an \texttt{nXn} unitary matrix over K, denotes the conjugate transpose of V. +\item SVD of matrix \texttt{m5} can be found out as, +\end{itemize} + +\begin{verbatim} + In []: svd(m5) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-14} + +\begin{itemize} +\item Matrices + +\begin{itemize} +\item creating matrices +\end{itemize} + +\item Matrix operations +\item Inverse (\texttt{inv()}) +\item Determinant (\texttt{det()}) +\item Norm (\texttt{norm()}) +\item Eigen values \& vectors (\texttt{eig(), eigvals()}) +\item Singular Value Decomposition (\texttt{svd()}) +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-15} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} + + +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d multiple-plots.rst --- a/multiple-plots.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,362 +0,0 @@ -Hello friends. Welcome to this spoken tutorial on Multiple plots. - -{{{ Show the slide containing the title }}} - -{{{ Show the slide containing the outline }}} - -In this tutorial, we will learn how to draw more than one plot, how to -add legends to each plot to indicate what each plot represents. We -will also learn how to switch between the plots and create multiple -plots with different regular axes which are also called as subplots. - -.. #[Nishanth]: See diff - edited a grammatical mistake -.. #[Madhu: Done] - -{{{ Shift to terminal and start ipython -pylab }}} - -To begin with let us start ipython with pylab, by typing:: - - ipython -pylab - -on the terminal - -Let us first create set of points for our plot. For this we will use -the command called linspace:: - - x = linspace(0, 50, 10) - -linspace command creates 10 points in the interval between 0 and 50 -both inclusive. We assign these values to a variable called x. - -.. #[Nishanth]: pre requisite for this LO is basic plotting which - covers linspace and plot. So you may not need to - specify all that again. But not a problem if it is - there also. -.. #[Madhu: Since I thought the LOs are disconnected, I thought it is - better to give a very short intro to it] - -Now let us draw a plot simple sine plot using these points:: - - plot(x, sin(x)) - -This should give us a nice sine plot. - -{{{ Switch to the plot window }}} - -Oh! wait! Is that a nice sine plot? Does a sine plot actually look -like that? We know that a sine plot is a smooth curve. Is it not? What -really caused this? - -.. #[Nishanth]: See diff -.. #[Madhu: Done] - -{{{ pause for a while }}} - -A small investigation on linspace tells us that we chose too few -points in a large interval between 0 and 50 for the curve to be -smooth. This should also indicate that the plot command actually plots -the set of points given by x and sin(x) and it doesn't plot the -analytical function itself i.e. it plots the points given by -Analytical functions. So now let us use linspace again to get 500 -points between 0 and 100 and draw the sine plot - -.. #[Nishanth]: Here specify that when we do plot(x, sin(x) - it is actually plotting two sets of points - and not analytical functions. Hence the sharp - curve. -.. #[Madhu: Incorporated] - -{{{ Switch to ipython andtype }}} :: - - y = linspace(0, 50, 500) - plot(y, sin(y)) - -{{{ Change to the plot window }}} - -Now we see what we remember as a sine plot. A smooth curve. If we -carefully notice we also have two plots now one overlaid upon -another. In pylab, by default all the plots are overlaid. - -Since we have two plots now overlaid upon each other we would like to -have a way to indicate what each plot represents to distinguish -between them. This is accomplished using legends. Equivalently, the -legend command does this for us - -{{{ Switch to ipython }}}:: - - legend(['sin(x)', 'cos(x)']) - -.. #[Nishanth]: This legend may go up in the script. May be before - introducing the figure command itself. -.. #[Madhu: brought up] - -The legend command takes a single list of parameters where each -parameter is the text indicating the plots in the order of their -serial number. - -{{{ Switch to plot window }}} - -Now we can see the legends being displayed for the respective sine and -cosine plots on the plot area. - -We have learnt quite a lot of things now, so let us take up an -exercise problem. - -%% 1 %% Draw two plots overlaid upon each other, with the first plot - being a parabola of the form y = 4(x ^ 2) and the second being a - straight line of the form y = 2x + 3 in the interval -5 to 5. Use - colors to differentiate between the plots and use legends to - indicate what each plot is doing. - -{{{ pause for a while and continue from paused state }}} - -We can obtain the two plots in different colors using the following -commands:: - - x = linspace(-5, 5, 100) - plot(x, 4 * (x * x), 'b') - plot(x, (2 * x) + 3, 'g') - -Now we can use the legend command as:: - - legend(['Parabola', 'Straight Line']) - -Or we can also just give the equations of the plot:: - - legend(['y = 4(x ^ 2)', 'y = 2x + 3']) - -We now know how to draw multiple plots and use legends to indicate -which plot represents what function, but we would like to have more -control over the plots we draw. Like switch between them, perform some -operations or labelling on them individually and so on. Let us see how -to accomplish this. Before we move on, let us clear our screen. - -{{{ Switch to ipython }}}:: - - clf() - -To accomplishing more control over individual plots we use the figure -command:: - - x = linspace(0, 50, 500) - figure(1) - plot(x, sin(x), 'b') - figure(2) - plot(x, cos(x), 'g') - -{{{ Switch to plot window }}} - -Now we have two plots, a sine plot and a cosine plot in two different -figures. - -.. #[Nishanth]: figure(1) and figure(2) give two different plots. - The remaining script moves on the fact that they - give overlaid plots which is not the case. - So clear the figure and plot cos and sin without - introducing figure command. Then introduce legend - and finish off the everything on legend. - Then introduce figure command. - -.. #[Madhu: I have just moved up the text about legend command. I - think that should take care of what you suggested. If there is - some mistake with it, Punch please let me know in your next - review.] - -{{{ Have both plot window and ipython side by side }}} - -The figure command takes an integer as an argument which is the serial -number of the plot. This selects the corresponding plot. All the plot -commands we run after this are applied to the selected plot. In this -example figure 1 is the sine plot and figure 2 is the cosine plot. We -can, for example, save each plot separately - -{{{ Switch to ipython }}}:: - - savefig('/home/user/cosine.png') - figure(1) - title('sin(y)') - savefig('/home/user/sine.png') - -{{{ Have both plot window and ipython side by side }}} - -We also titled the our first plot as 'sin(y)' which we did not do for -the second plot. - -Let us attempt another exercise problem - -%% 2 %% Draw a line of the form y = x as one figure and another line - of the form y = 2x + 3. Switch back to the first figure, annotate - the x and y intercepts. Now switch to the second figure and - annotate its x and y intercepts. Save each of them. - -{{{ Pause for a while and continue from the paused state }}} - -To solve this problem we should first create the first figure using -the figure command. Before that, let us first run clf command to make -sure all the previous plots are cleared:: - - clf() - figure(1) - x = linspace(-5, 5, 100) - plot(x, x) - -Now we can use figure command to create second plotting area and plot -the figure:: - - figure(2) - plot(x, ((2 * x) + 3)) - -Now to switch between the figures we can use figure command. So let us -switch to figure 1. We are asked to annotate x and y intercepts of the -figure 1 but since figure 1 passes through origin we will have to -annotate the origin. We will annotate the intercepts for the second -figure and save them as follows:: - - figure(1) - annotate('Origin', xy=(0.0, 0.0) - figure(2) - annotate('x-intercept', xy=(0, 3)) - annotate('y-intercept', xy=(0, -1.5)) - savefig('/home/fossee/plot2.png') - figure(1) - savefig('/home/fossee/plot1.png') - -At times we run into situations where we want to compare two plots and -in such cases we want to draw both the plots in the same plotting -area. The situation is such that the two plots have different regular -axes which means we cannot draw overlaid plots. In such cases we can -draw subplots. - -We use subplot command to accomplish this - -{{{ Switch to ipython }}}:: - - subplot(2, 1, 1) - -subplot command takes three arguments, the first being the number of -rows of subplots that must be created, - -{{{ Have both plot window and ipython side by side }}} - -in this case we have 2 so it spilts the plotting area horizontally for -two subplots. The second argument specifies the number of coloumns of -subplots that must be created. We passed 1 as the argument so the -plotting area won't be split vertically and the last argument -specifies what subplot must be created now in the order of the serial -number. In this case we passed 1 as the argument, so the first subplot -that is top half is created. If we execute the subplot command as - -{{{ Switch to ipython }}}:: - - subplot(2, 1, 2) - -{{{ Switch to plot window }}} - -The lower subplot is created. Now we can draw plots in each of the -subplot area using the plot command. - -{{{ Switch to ipython }}}:: - - x = linspace(0, 50, 500) - plot(x, cos(x)) - subplot(2, 1, 1) - y = linspace(0, 5, 100) - plot(y, y ** 2) - -{{{ Have both plot window and ipython side by side }}} - -This created two plots one in each of the subplot area. The top -subplot holds a parabola and the bottom subplot holds a cosine -curve. - -As seen here we can use subplot command to switch between the subplot -as well, but we have to use the same arguments as we used to create -that subplot, otherwise the previous subplot at that place will be -automatically erased. It is clear from the two subplots that both have -different regular axes. For the cosine plot x-axis varies from 0 to -100 and y-axis varies from 0 to 1 where as for the parabolic plot the -x-axis varies from 0 to 10 and y-axis varies from 0 to 100 - -.. #[Nishanth]: stress on the similarity between subplot and figure - commands - -.. #[Madhu: I think they are not really similar. Trying to bring in - the similarity will confuse people I think.] - -%% 3 %% We know that the Pressure, Volume and Temperatures are held by -the equation PV = nRT where nR is a constant. Let us assume nR = .01 -Joules/Kelvin and T = 200K. V can be in the range from 21cc to -100cc. Draw two different plots as subplots, one being the Pressure -versus Volume plot and the other being Pressure versus Temparature -plot. - -{{{ Pause for a while and continue }}} - -To start with, we have been given the range of Volume using which we -can define the variable V:: - - V = linspace(21, 100, 500) - -Now we can create first subplot and draw Pressure versus Volume graph -using this V. We know that nRT is a constant which is equal to 2.0 -since nR = 0.01 Joules/Kelvin and T = 200 Kelvin:: - - subplot(2, 1, 1) - plot(V, 2.0/V) - -Now we can create the second subplot and draw the Pressure versus -Temparature plot as follows:: - - subplot(2, 1, 2) - plot(200, 2.0/V) - -Unfortunately we have an error now, telling x and y dimensions don't -match. This is because our V contains a set of values as returned by -linspace and hence 2.0/V which is the pressure also contains a set of -values. But the first argument to the plot command is a single -value. So to plot this data we need to create as many points as there -are in Pressure or Volume data for Temperature too, all having the -same value. This can be accomplished using:: - - T = linspace(200, 200, 500) - -We now have 500 values in T each with the value 200 Kelvin. Plotting -this data we get the required plot:: - - plot(T, 2.0/V) - -It is left as a homework to label both X and Y axes for each of the -two subplots. - -{{{ Show summary slide }}} - -.. #[Nishanth]: Exercises are missing in the script - one exercise for overlaid plot and legend - one for figure command - one for subplot must do - -This brings us to the end of another session. In this tutorial session -we learnt - - * How to draw multiple plots which are overlaid - * the figure command - * the legend command - * how to switch between the plots and perform some operations on each - of them like saving the plots and - * creating and switching between subplots - -.. #[Nishanth]: legend command can be told right after overlaid plots -.. #[Madhu: Incorporated] - -{{{ Show the "sponsored by FOSSEE" slide }}} - -This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India - -Hope you have enjoyed and found it useful. -Thankyou - -.. Author : Madhu - Internal Reviewer 1 : [potential reviewer: Puneeth] - Internal Reviewer 2 : Nishanth - External Reviewer : - diff -r e675f9208b91 -r 4054b1a6392d multiple-plots/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple-plots/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,89 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. Multiple plots appear in different figures by default. True or False? + + Answer: False + +#. What command is used to get individual plots separately? + + Answer: Figure + +#. Which figure is closed after the following commands are run? + +:: + + x = linspace(0, 50, 500) + figure(1) + plot(x, sin(x), 'b') + figure(2) + plot(x, cos(x), 'g') + xlabel('x') + ylabel('cos(x)') + close() + + Answer: Figure 2 + +#. Describe the plot obtained by the following commands:: + + x = linspace(0, 50, 500) + subplot(2, 1, 1) + plot(x, sin(x), 'b') + +Answer: A figure window with space for 2 plots one below the other is + obtained. The sine plot with blue line appears in the first row. + +#. Describe the plot obtained by the following commands:: + + x = linspace(0, 50, 500) + subplot(2, 1, 1) + plot(x, sin(x), 'b') + subplot(2, 1, 2) + plot(x, cos(x), 'g') + + Answer: 2 plots one below another. sine in blue on first row. cosine + in green in the second row. + +#. Describe the plot obtained by the following commands:: + + x = linspace(0, 50, 500) + subplot(2, 1, 1) + plot(x, sin(x), 'b') + subplot(2, 1, 2) + plot(x, cos(x), 'g') + subplot(2, 1, 1) + plot(x, tan(x), 'r') + + Answer: 2 plots one below another. tan in red on first row. cosine + in green in the second row. + + +#. Which of the following gives the correct legend for the commands below + + a. legend([sin, cos, tan]) + #. legend([tan, cos, sin]) + #. legend[(tan, cos, sin)] + #. legend(['sin', 'cos', 'tan']) + #. legend(['tan', 'cos', 'sin']) + +:: + + x = linspace(0, 50, 500) + figure(1) + plot(x, sin(x), 'b') + figure(2) + plot(x, cos(x), 'g') + figure(3) + plot(x, tan(x), 'b') + + Answer: legend(['tan', 'cos', 'sin']) + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Question 1 +2. Question 2 diff -r e675f9208b91 -r 4054b1a6392d multiple-plots/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple-plots/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,383 @@ +.. Objectives +.. ---------- + +.. * How to draw multiple plots which are overlaid +.. * the figure command +.. * the legend command +.. * how to switch between the plots and perform some operations on each +.. of them like saving the plots and +.. * creating and switching between subplots + + +.. Prerequisites +.. ------------- + +.. 1. using the plot command interactively +.. 2. embellishing a plot +.. 3. saving plots + +.. Author : Madhu + Internal Reviewer 1 : [potential reviewer: Puneeth] + Internal Reviewer 2 : Nishanth + External Reviewer : + +Script +------ + +{{{ Show the slide containing the title }}} + +Hello friends. Welcome to this spoken tutorial on Multiple plots. + +{{{ Show the slide containing the outline }}} + +In this tutorial, we will learn how to draw more than one plot, how to +add legends to each plot to indicate what each plot represents. We +will also learn how to switch between the plots and create multiple +plots with different regular axes which are also called as subplots. + +.. #[Nishanth]: See diff - edited a grammatical mistake +.. #[Madhu: Done] + +{{{ Shift to terminal and start ipython -pylab }}} + +To begin with let us start ipython with pylab, by typing:: + + ipython -pylab + +on the terminal + +Let us first create set of points for our plot. For this we will use +the command called linspace:: + + x = linspace(0, 50, 10) + +linspace command creates 10 points in the interval between 0 and 50 +both inclusive. We assign these values to a variable called x. + +.. #[Nishanth]: pre requisite for this LO is basic plotting which + covers linspace and plot. So you may not need to + specify all that again. But not a problem if it is + there also. +.. #[Madhu: Since I thought the LOs are disconnected, I thought it is + better to give a very short intro to it] + +Now let us draw a plot simple sine plot using these points:: + + plot(x, sin(x)) + +This should give us a nice sine plot. + +{{{ Switch to the plot window }}} + +Oh! wait! Is that a nice sine plot? Does a sine plot actually look +like that? We know that a sine plot is a smooth curve. Is it not? What +really caused this? + +.. #[Nishanth]: See diff +.. #[Madhu: Done] + +{{{ pause for a while }}} + +A small investigation on linspace tells us that we chose too few +points in a large interval between 0 and 50 for the curve to be +smooth. This should also indicate that the plot command actually plots +the set of points given by x and sin(x) and it doesn't plot the +analytical function itself i.e. it plots the points given by +Analytical functions. So now let us use linspace again to get 500 +points between 0 and 100 and draw the sine plot + +.. #[Nishanth]: Here specify that when we do plot(x, sin(x) + it is actually plotting two sets of points + and not analytical functions. Hence the sharp + curve. +.. #[Madhu: Incorporated] + +{{{ Switch to ipython andtype }}} :: + + y = linspace(0, 50, 500) + plot(y, sin(y)) + +{{{ Change to the plot window }}} + +Now we see what we remember as a sine plot. A smooth curve. If we +carefully notice we also have two plots now one overlaid upon +another. In pylab, by default all the plots are overlaid. + +Since we have two plots now overlaid upon each other we would like to +have a way to indicate what each plot represents to distinguish +between them. This is accomplished using legends. Equivalently, the +legend command does this for us + +{{{ Switch to ipython }}}:: + + legend(['sin(x)', 'cos(x)']) + +.. #[Nishanth]: This legend may go up in the script. May be before + introducing the figure command itself. +.. #[Madhu: brought up] + +The legend command takes a single list of parameters where each +parameter is the text indicating the plots in the order of their +serial number. + +{{{ Switch to plot window }}} + +Now we can see the legends being displayed for the respective sine and +cosine plots on the plot area. + +We have learnt quite a lot of things now, so let us take up an +exercise problem. + +%% 1 %% Draw two plots overlaid upon each other, with the first plot + being a parabola of the form y = 4(x ^ 2) and the second being a + straight line of the form y = 2x + 3 in the interval -5 to 5. Use + colors to differentiate between the plots and use legends to + indicate what each plot is doing. + +{{{ pause for a while and continue from paused state }}} + +We can obtain the two plots in different colors using the following +commands:: + + x = linspace(-5, 5, 100) + plot(x, 4 * (x * x), 'b') + plot(x, (2 * x) + 3, 'g') + +Now we can use the legend command as:: + + legend(['Parabola', 'Straight Line']) + +Or we can also just give the equations of the plot:: + + legend(['y = 4(x ^ 2)', 'y = 2x + 3']) + +We now know how to draw multiple plots and use legends to indicate +which plot represents what function, but we would like to have more +control over the plots we draw. Like switch between them, perform some +operations or labelling on them individually and so on. Let us see how +to accomplish this. Before we move on, let us clear our screen. + +{{{ Switch to ipython }}}:: + + clf() + +To accomplishing more control over individual plots we use the figure +command:: + + x = linspace(0, 50, 500) + figure(1) + plot(x, sin(x), 'b') + figure(2) + plot(x, cos(x), 'g') + +{{{ Switch to plot window }}} + +Now we have two plots, a sine plot and a cosine plot in two different +figures. + +.. #[Nishanth]: figure(1) and figure(2) give two different plots. + The remaining script moves on the fact that they + give overlaid plots which is not the case. + So clear the figure and plot cos and sin without + introducing figure command. Then introduce legend + and finish off the everything on legend. + Then introduce figure command. + +.. #[Madhu: I have just moved up the text about legend command. I + think that should take care of what you suggested. If there is + some mistake with it, Punch please let me know in your next + review.] + +{{{ Have both plot window and ipython side by side }}} + +The figure command takes an integer as an argument which is the serial +number of the plot. This selects the corresponding plot. All the plot +commands we run after this are applied to the selected plot. In this +example figure 1 is the sine plot and figure 2 is the cosine plot. We +can, for example, save each plot separately + +{{{ Switch to ipython }}}:: + + savefig('/home/user/cosine.png') + figure(1) + title('sin(y)') + savefig('/home/user/sine.png') + +{{{ Have both plot window and ipython side by side }}} + +We also titled the our first plot as 'sin(y)' which we did not do for +the second plot. + +Let us attempt another exercise problem + +%% 2 %% Draw a line of the form y = x as one figure and another line + of the form y = 2x + 3. Switch back to the first figure, annotate + the x and y intercepts. Now switch to the second figure and + annotate its x and y intercepts. Save each of them. + +{{{ Pause for a while and continue from the paused state }}} + +To solve this problem we should first create the first figure using +the figure command. Before that, let us first run clf command to make +sure all the previous plots are cleared:: + + clf() + figure(1) + x = linspace(-5, 5, 100) + plot(x, x) + +Now we can use figure command to create second plotting area and plot +the figure:: + + figure(2) + plot(x, ((2 * x) + 3)) + +Now to switch between the figures we can use figure command. So let us +switch to figure 1. We are asked to annotate x and y intercepts of the +figure 1 but since figure 1 passes through origin we will have to +annotate the origin. We will annotate the intercepts for the second +figure and save them as follows:: + + figure(1) + annotate('Origin', xy=(0.0, 0.0) + figure(2) + annotate('x-intercept', xy=(0, 3)) + annotate('y-intercept', xy=(0, -1.5)) + savefig('/home/fossee/plot2.png') + figure(1) + savefig('/home/fossee/plot1.png') + +At times we run into situations where we want to compare two plots and +in such cases we want to draw both the plots in the same plotting +area. The situation is such that the two plots have different regular +axes which means we cannot draw overlaid plots. In such cases we can +draw subplots. + +We use subplot command to accomplish this + +{{{ Switch to ipython }}}:: + + subplot(2, 1, 1) + +subplot command takes three arguments, the first being the number of +rows of subplots that must be created, + +{{{ Have both plot window and ipython side by side }}} + +in this case we have 2 so it spilts the plotting area horizontally for +two subplots. The second argument specifies the number of coloumns of +subplots that must be created. We passed 1 as the argument so the +plotting area won't be split vertically and the last argument +specifies what subplot must be created now in the order of the serial +number. In this case we passed 1 as the argument, so the first subplot +that is top half is created. If we execute the subplot command as + +{{{ Switch to ipython }}}:: + + subplot(2, 1, 2) + +{{{ Switch to plot window }}} + +The lower subplot is created. Now we can draw plots in each of the +subplot area using the plot command. + +{{{ Switch to ipython }}}:: + + x = linspace(0, 50, 500) + plot(x, cos(x)) + subplot(2, 1, 1) + y = linspace(0, 5, 100) + plot(y, y ** 2) + +{{{ Have both plot window and ipython side by side }}} + +This created two plots one in each of the subplot area. The top +subplot holds a parabola and the bottom subplot holds a cosine +curve. + +As seen here we can use subplot command to switch between the subplot +as well, but we have to use the same arguments as we used to create +that subplot, otherwise the previous subplot at that place will be +automatically erased. It is clear from the two subplots that both have +different regular axes. For the cosine plot x-axis varies from 0 to +100 and y-axis varies from 0 to 1 where as for the parabolic plot the +x-axis varies from 0 to 10 and y-axis varies from 0 to 100 + +.. #[Nishanth]: stress on the similarity between subplot and figure + commands + +.. #[Madhu: I think they are not really similar. Trying to bring in + the similarity will confuse people I think.] + +%% 3 %% We know that the Pressure, Volume and Temperatures are held by +the equation PV = nRT where nR is a constant. Let us assume nR = .01 +Joules/Kelvin and T = 200K. V can be in the range from 21cc to +100cc. Draw two different plots as subplots, one being the Pressure +versus Volume plot and the other being Pressure versus Temparature +plot. + +{{{ Pause for a while and continue }}} + +To start with, we have been given the range of Volume using which we +can define the variable V:: + + V = linspace(21, 100, 500) + +Now we can create first subplot and draw Pressure versus Volume graph +using this V. We know that nRT is a constant which is equal to 2.0 +since nR = 0.01 Joules/Kelvin and T = 200 Kelvin:: + + subplot(2, 1, 1) + plot(V, 2.0/V) + +Now we can create the second subplot and draw the Pressure versus +Temparature plot as follows:: + + subplot(2, 1, 2) + plot(200, 2.0/V) + +Unfortunately we have an error now, telling x and y dimensions don't +match. This is because our V contains a set of values as returned by +linspace and hence 2.0/V which is the pressure also contains a set of +values. But the first argument to the plot command is a single +value. So to plot this data we need to create as many points as there +are in Pressure or Volume data for Temperature too, all having the +same value. This can be accomplished using:: + + T = linspace(200, 200, 500) + +We now have 500 values in T each with the value 200 Kelvin. Plotting +this data we get the required plot:: + + plot(T, 2.0/V) + +It is left as a homework to label both X and Y axes for each of the +two subplots. + +{{{ Show summary slide }}} + +.. #[Nishanth]: Exercises are missing in the script + one exercise for overlaid plot and legend + one for figure command + one for subplot must do + +This brings us to the end of another session. In this tutorial session +we learnt + + * How to draw multiple plots which are overlaid + * the figure command + * the legend command + * how to switch between the plots and perform some operations on each + of them like saving the plots and + * creating and switching between subplots + +.. #[Nishanth]: legend command can be told right after overlaid plots +.. #[Madhu: Incorporated] + +{{{ Show the "sponsored by FOSSEE" slide }}} + +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you! + diff -r e675f9208b91 -r 4054b1a6392d multiple-plots/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple-plots/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,123 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Accessing parts of arrays +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Manipulating one and multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slicing and striding on arrays to access chunks + - Read images into arrays and manipulations +* Sample Arrays + #+begin_src python + In []: A = array([12, 23, 34, 45, 56]) + + In []: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) + + #+end_src +* Question 1 + Change the last column of ~C~ to zeroes. +* Solution 1 + #+begin_src python + In []: C[:, -1] = 0 + #+end_src +* Question 2 + Change ~A~ to ~[11, 12, 13, 14, 15]~. +* Solution 2 + #+begin_src python + In []: A[:] = [11, 12, 13, 14, 15] + #+end_src +* squares.png + #+begin_latex + \begin{center} + \includegraphics[scale=0.6]{squares} + \end{center} + #+end_latex +* Question 3 + - obtain ~[22, 23]~ from ~C~. + - obtain ~[11, 21, 31, 41]~ from ~C~. + - obtain ~[21, 31, 41, 0]~. +* Solution 3 + #+begin_src python + In []: C[1, 1:3] + In []: C[0:4, 0] + In []: C[1:5, 0] + #+end_src +* Question 4 + Obtain ~[[23, 24], [33, -34]]~ from ~C~ +* Solution 4 + #+begin_src python + In []: C[1:3, 2:4] + #+end_src +* Question 5 + Obtain the square in the center of the image +* Solution 5 + #+begin_src python + In []: imshow(I[75:225, 75:225]) + #+end_src +* Question 6 + Obtain the following + #+begin_src python + [[12, 0], [42, 0]] + [[12, 13, 14], [0, 0, 0]] + #+end_src + +* Solution 6 + #+begin_src python + In []: C[::3, 1::3] + In []: C[::4, 1:4] + #+end_src +* Summary + You should now be able to -- + - Manipulate 1D \& Multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slice and stride on arrays + - Read images into arrays and manipulate them. +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d multiple-plots/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/multiple-plots/slides.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d other-type-of-plots/bar-chart-hatch.png Binary file other-type-of-plots/bar-chart-hatch.png has changed diff -r e675f9208b91 -r 4054b1a6392d other-type-of-plots/company-a-data.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other-type-of-plots/company-a-data.txt Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,2 @@ +2.000000000000000000e+03 2.001000000000000000e+03 2.002000000000000000e+03 2.003000000000000000e+03 2.004000000000000000e+03 2.005000000000000000e+03 2.006000000000000000e+03 2.007000000000000000e+03 2.008000000000000000e+03 2.009000000000000000e+03 2.010000000000000000e+03 +2.300000000000000000e+01 5.500000000000000000e+01 3.200000000000000000e+01 6.500000000000000000e+01 8.800000000000000000e+01 5.000000000000000000e+00 1.400000000000000000e+01 6.700000000000000000e+01 2.300000000000000000e+01 2.300000000000000000e+01 1.200000000000000000e+01 diff -r e675f9208b91 -r 4054b1a6392d other-type-of-plots/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other-type-of-plots/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,85 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. What is a log-log chart? + + a. A straight line graph + #. A graph on the logarithmic scale + #. A graph on the logarithmic scale with different scales for x and + y axes + #. A graph in which x axis is represented in logarithmic scale. + +Answer: A graph on the logarithmic scale with different scales for x + and y axes + +2. We have two lists with us ``years`` and ``profit``, what statement + can be issued to plot a pie chart to plot the profit for each year, + and each wedge has to be labelled with the corresponding year. + +Answer: pie(profit, labels=years) + +3. We have two lists with us ``years`` and profit``, what statement + can be issued to plot a scatter plot of the data in blue colored + diamonds. ``years`` has to be plotted along x-axis. + +Answer: scatter(year,profit,color='blue',marker='d') + +4. ``scatter(x, y, color='blue', marker='d')`` and ``plot(x, y, + color='b', marker='d')`` does exactly the same. + + a. True + #. False + +Answer: False + +5. ``plot(x, y, 'bd')`` creates a scattered plot in blue color and + diamond markers? + + a. True + #. False + +Answer: True + +6. ``scatter(x, y, 'bd')`` creates a scatter plot in blue color with + diamond markers. + + a. True + #. False + +Answer: False + +7. What statement can be issued to generate a bar chart with 135\ + :sup:`o` hatched bar filled with white. + + a. bar(x, y, color='w', hatch='/') + #. bar(x, y, color='w', hatch='\\') + #. bar(x, y, color='w', hatch='\') + #. bar(x, y, color='w', hatch='|') + +Answer: bar(x, y, color='w', hatch='\\') + +8. What statement can be issued to generate a bar chart with vertical + line hatching. + + a. bar(x, y, color='w', hatch='/') + #. bar(x, y, fill=False, hatch='\\') + #. bar(x, y, fill=False, hatch='|') + #. bar(x, y, color='w', hatch='\') + +Answer: bar(x, y, fill=False, hatch='|') + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Plot a log-log chart of the equation y=4*x\ :sup:`2` + 3*x for x + from -50 to 50. + +2. Plot a bar chart which is filled with white color and which is + hatched with 135\ :sup:`o` slanting lines for the data given in the + `file(company A data) `_ which has years and + profit percentage for each year. + diff -r e675f9208b91 -r 4054b1a6392d other-type-of-plots/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other-type-of-plots/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,241 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Create scatter plot +.. #. Create pie charts +.. #. Create bar charts +.. #. Create log-log plots. + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` and ``pylab`` installed. +.. #. getting started with ``ipython``. +.. #. loading data from files +.. #. plotting the data + + +.. Author : Anoop Jacob Thomas + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + + +=================== +Other type of plots +=================== + +{{{ show the first slide }}} + +Hello and welcome to the tutorial other type of plots. + +{{{ show the outline slide }}} + +In this tutorial we will cover scatter plot, pie chart, bar chart and +loglog plot. We will also see few other plots and also introduce you to +the matplotlib help. + +Let us start with scatter plot. + +{{{ switch to the next slide, scatter plot }}} + +In a scatter plot, the data is displayed as a collection of points, +each having the value of one variable determining the position on the +horizontal axis and the value of the other variable determining the +position on the vertical axis. This kind of plot is also called a +scatter chart, scatter diagram and scatter graph. + +Before we proceed further get your IPython interpreter running with +the ``-pylab`` option. Start your IPython interpreter as +:: + + ipython -pylab + +{{{ open the ipython interpreter in the terminal using the command +ipython -pylab }}} + +{{{ switch to the next slide having the problem statement of first +exercise }}} + +Now, let us plot a scatter plot showing the percentage profit of company A +from the year 2000-2010. The data for the same is available in the +file ``company-a-data.txt``. + +{{{ open the file company-a-data.txt and show the content }}} + +The data file has two lines with a set of values in each line, the +first line representing years and the second line representing the +profit percentages. + +{{{ close the file and switch to the terminal }}} + +To produce the scatter plot first we need to load the data from the +file using ``loadtxt``. We learned it in one of the previous sessions, +and it can be done as :: + + year,profit = + loadtxt('/home/fossee/other-plot/company-a-data.txt',dtype=type(int())) + +{{{ switch to next slide, ``scatter`` function }}} + +Now in-order to generate the scatter graph we will use the function +``scatter()`` +:: + + scatter(year,profit) + +Notice that we passed two arguments to ``scatter()`` function, first +one the values in x-coordinate, year, and the other the values in +y-coordinate, the profit percentage. + +{{{ switch to the next slide which has the problem statement of +problem to be tried out }}} + +Now here is a question for you to try out, plot the same data with red +diamonds markers. + +.. **Clue** - *try scatter? in your ipython interpreter* + +Pause here and solve the question before moving on. + +.. scatter(year,profit,color='r',marker='d') + +Now let us move on to pie chart. + +{{{ switch to the slide which says about pie chart }}} + +A pie chart or a circle graph is a circular chart divided into +sectors, illustrating proportion. + +{{{ switch to the slide showing the problem statement of second +exercise question }}} + +Plot a pie chart representing the profit percentage of company A, with +the same data from file ``company-a-data.txt``. So let us reuse the +data we have loaded from the file previously. + +{{{ switch to next slide, ``pie()`` function }}} + +We can plot the pie chart using the function ``pie()``. +:: + + pie(profit,labels=year) + +Notice that we passed two arguments to the function ``pie()``. First +one the values and the next one the set of labels to be used in the +pie chart. + +{{{ switch to the next slide which has the problem statement of +problem to be tried out }}} + +Now here is a question for you to try out, plot a pie chart with the +same data with colors for each wedges as white, red, black, magenta, +yellow, blue, green, cyan, yellow, magenta and blue respectively. + +.. **Clue** - *try pie? in your ipython interpreter* + +Pause here and solve the question before moving on. + +.. pie(t,labels=s,colors=('w','r','k','m','y','b','g','c','y','m','b')) + +{{{ switch to the slide which says about bar chart }}} + +Now let us move on to bar chart. A bar chart or bar graph is a chart +with rectangular bars with lengths proportional to the values that +they represent. + +{{{ switch to the slide showing the problem statement of fifth +exercise question }}} + +Plot a bar chart representing the profit percentage of company A, with +the same data from file ``company-a-data.txt``. + +So let us reuse the data we have loaded from the file previously. + +{{{ switch to the next slide, ``bar()`` function }}} + +We can plot the bar chart using the function ``bar()``. +:: + + bar(year,profit) + +Note that the function ``bar()`` needs at least two arguments one the +values in x-coordinate and the other values in y-coordinate which is +used to determine the height of the bars. + +{{{ switch to the next slide which has the problem statement of +problem to be tried out }}} + +Now here is a question for you to try, plot a bar chart which is not +filled and which is hatched with 45\ :sup:`o` slanting lines as shown +in the image in the slide. The data for the chart may be obtained from +the file ``company-a-data.txt``. + +.. **Clue** - *try bar? in your ipython interpreter* + +.. bar(year,profit,fill=False,hatch='/') + +{{{ switch to the slide which says about log-log graph }}} + +Now let us move on to log-log plot. A log-log graph or log-log plot is +a two-dimensional graph of numerical data that uses logarithmic scales +on both the horizontal and vertical axes. Because of the nonlinear +scaling of the axes, a function of the form y = ax\ :sup:`b` will +appear as a straight line on a log-log graph + +{{{ switch to the slide showing the problem statement of fourth +exercise question }}} + + +Plot a `log-log` chart of y=5*x\ :sup:`3` for x from 1-20. + +Before we actually plot let us calculate the points needed for +that. And it could be done as, +:: + + x = linspace(1,20,100) + y = 5*x**3 + +{{{ switch to next slide, ``loglog()`` function }}} + +Now we can plot the log-log chart using ``loglog()`` function, +:: + + loglog(x,y) + +To understand the difference between a normal ``plot`` and a ``log-log +plot`` let us create another plot using the function ``plot``. +:: + + figure(2) + plot(x,y) + +{{{ show both the plots side by side }}} + +So that was ``log-log() plot``. + +{{{ switch to the next slide which says: "How to get help on +matplotlib online"}}} + +Now we will see few more plots and also see how to access help of +matplotlib over the internet. + +Help about matplotlib can be obtained from +matplotlib.sourceforge.net/contents.html + + +More plots can be seen at +matplotlib.sourceforge.net/users/screenshots.html and also at +matplotlib.sourceforge.net/gallery.html + +{{{ switch to summary slide }}} + +Now we have come to the end of this tutorial. We have covered scatter +plot, pie chart, bar chart, log-log plot and also saw few other plots +and covered how to access the matplotlib online help. + +{{{ switch to the thank you slide }}} + +Thank you! diff -r e675f9208b91 -r 4054b1a6392d other-type-of-plots/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other-type-of-plots/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,137 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Other type of plots +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Scatter plot + - Pie chart + - Bar chart + - Log-log Plot + - ~matplotlib~ help +* Exercise 1: Scatter plot + Plot a scatter plot showing the percentage profit of Company A from the year 2000 + to 2010. The data for the same is available in the file ~company-a-data.txt~. +* ~scatter()~ function + - /Syntax :/ scatter(x,y) + - x, a sequence of data + - y, a sequence of data, the same length of x + : In []: scatter(year, profit) +* Exercise 2: Scatter plot + Plot a scatter plot of the same data in ~company-a-data.txt~ with red diamond markers. + : + *Clue* - /try scatter? in your ipython interpreter/ +* Pie chart + Pie chart - a circle graph divided into sectors, illustrating proportion. +* Exercise 3: Pie chart + Plot a pie chart representing the profit percentage of company A, with the data + from the file ~company-a-data.txt~. + : + /(we can reuse the data in lists year and profit)/ +* ~pie()~ function + - /Syntax :/ pie(values, labels=labels) + - values, the data to be plotted + - labels, the label for each wedge in the pie chart + : In []: pie(profit, labels=year) +* Exercise 4: Pie chart + Plot a pie chart with the same data with colors for each wedges as white, red, + magenta, yellow, blue, green, cyan, yellow, magenta, and blue. + : + *Clue* - /try pie? in your ipython interpreter/ +* Bar chart + Bar chart - a chart with rectangular bars with lengths proportional + to the values that they represent. +* Exercise 5: Bar chart + Plot a bar chart representing the profit percentage of company A, with the data + from the file ~company-a-data.txt~. + : + /(we can reuse the data in lists year and profit)/ +* ~bar()~ function + - /Syntax :/ bar(x, y) + - x, a sequence of data + - y, a sequence of data, the same length of x + : In []: bar(year, profit) +* Exercise 6: Bar chart + Plot a bar chart which is not filled and which is hatched with + #+begin_latex + $45^o$ + #+end_latex + slanting lines as shown in the image. The data for the chart may be + obtained from the file ~company-a-data.txt~. + #+begin_latex + \begin{center} + \includegraphics[scale=0.3]{bar-chart-hatch} + \end{center} + #+end_latex + *Clue* - /try bar? in your ipython interpreter/ +* Log-log graph + - Log-log graph + - 2-dimensional graph. + - uses logarithmic scales on both axes. + - graph appears as straight line due to non-linear scaling. +* Exercise 7: + Plot a log-log chart of + #+begin_latex + $y = 5x^3$ + #+end_latex + for x from 1-20. +* ~loglog()~ function + - /Syntax :/ loglog(x, y) + - x, a sequence of data + - y, a sequence of data, the same length of x + : In []: loglog(x, y) +* Getting help on ~matplotlib~ + - Help + - [[matplotlib.sourceforge.net/contents.html]] + - More plots + - [[matplotlib.sourceforge.net/users/screenshots.html]] + - [[matplotlib.sourceforge.net/gallery.html]] + +* Summary + - Scatter plot (~scatter()~) + - Pie chart (~pie()~) + - Bar chart (~bar()~) + - Log-log plot (~loglog()~) + - ~matplotlib~ online help +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d other-type-of-plots/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/other-type-of-plots/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,280 @@ +% Created 2010-10-12 Tue 16:22 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Other type of plots} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Scatter plot +\item Pie chart +\item Bar chart +\item Log-log Plot +\item \texttt{matplotlib} help +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 1: Scatter plot} +\label{sec-2} + + Plot a scatter plot showing the percentage profit of Company A from the year 2000 + to 2010. The data for the same is available in the file \texttt{company-a-data.txt}. +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{scatter()} function} +\label{sec-3} + +\begin{itemize} +\item \emph{Syntax :} scatter(x,y) + +\begin{itemize} +\item x, a sequence of data +\item y, a sequence of data, the same length of x +\end{itemize} + +\end{itemize} + +\begin{verbatim} + In []: scatter(year, profit) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 2: Scatter plot} +\label{sec-4} + + Plot a scatter plot of the same data in \texttt{company-a-data.txt} with red diamond markers. +\begin{verbatim} + +\end{verbatim} + + \textbf{Clue} - \emph{try scatter? in your ipython interpreter} +\end{frame} +\begin{frame} +\frametitle{Pie chart} +\label{sec-5} + + Pie chart - a circle graph divided into sectors, illustrating proportion. +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 3: Pie chart} +\label{sec-6} + + Plot a pie chart representing the profit percentage of company A, with the data + from the file \texttt{company-a-data.txt}. +\begin{verbatim} + +\end{verbatim} + + \emph{(we can reuse the data in lists year and profit)} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{pie()} function} +\label{sec-7} + +\begin{itemize} +\item \emph{Syntax :} pie(values, labels=labels) + +\begin{itemize} +\item values, the data to be plotted +\item labels, the label for each wedge in the pie chart +\end{itemize} + +\end{itemize} + +\begin{verbatim} + In []: pie(profit, labels=year) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 4: Pie chart} +\label{sec-8} + + Plot a pie chart with the same data with colors for each wedges as white, red, + magenta, yellow, blue, green, cyan, yellow, magenta, and blue. +\begin{verbatim} + +\end{verbatim} + + \textbf{Clue} - \emph{try pie? in your ipython interpreter} +\end{frame} +\begin{frame} +\frametitle{Bar chart} +\label{sec-9} + + Bar chart - a chart with rectangular bars with lengths proportional + to the values that they represent. +\end{frame} +\begin{frame}[fragile] +\frametitle{Exercise 5: Bar chart} +\label{sec-10} + + Plot a bar chart representing the profit percentage of company A, with the data + from the file \texttt{company-a-data.txt}. +\begin{verbatim} + +\end{verbatim} + + \emph{(we can reuse the data in lists year and profit)} +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{bar()} function} +\label{sec-11} + +\begin{itemize} +\item \emph{Syntax :} bar(x, y) + +\begin{itemize} +\item x, a sequence of data +\item y, a sequence of data, the same length of x +\end{itemize} + +\end{itemize} + +\begin{verbatim} + In []: bar(year, profit) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Exercise 6: Bar chart} +\label{sec-12} + + Plot a bar chart which is not filled and which is hatched with + $45^o$ + slanting lines as shown in the image. The data for the chart may be + obtained from the file \texttt{company-a-data.txt}. + \begin{center} + \includegraphics[scale=0.3]{bar-chart-hatch} + \end{center} + \textbf{Clue} - \emph{try bar? in your ipython interpreter} +\end{frame} +\begin{frame} +\frametitle{Log-log graph} +\label{sec-13} + +\begin{itemize} +\item Log-log graph + +\begin{itemize} +\item 2-dimensional graph. +\item uses logarithmic scales on both axes. +\item graph appears as straight line due to non-linear scaling. +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Exercise 7:} +\label{sec-14} + + Plot a log-log chart of + $y = 5x^3$ + for x from 1-20. +\end{frame} +\begin{frame}[fragile] +\frametitle{\texttt{loglog()} function} +\label{sec-15} + +\begin{itemize} +\item \emph{Syntax :} loglog(x, y) + +\begin{itemize} +\item x, a sequence of data +\item y, a sequence of data, the same length of x +\end{itemize} + +\end{itemize} + +\begin{verbatim} + In []: loglog(x, y) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Getting help on \texttt{matplotlib}} +\label{sec-16} + +\begin{itemize} +\item Help + +\begin{itemize} +\item \hyperref[sec-16]{matplotlib.sourceforge.net/contents.html} +\end{itemize} + +\item More plots + +\begin{itemize} +\item \hyperref[sec-16]{matplotlib.sourceforge.net/users/screenshots.html} +\item \hyperref[sec-16]{matplotlib.sourceforge.net/gallery.html} +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-17} + +\begin{itemize} +\item Scatter plot (\texttt{scatter()}) +\item Pie chart (\texttt{pie()}) +\item Bar chart (\texttt{bar()}) +\item Log-log plot (\texttt{loglog()}) +\item \texttt{matplotlib} online help +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-18} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d other_type_of_plots.rst --- a/other_type_of_plots.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,220 +0,0 @@ -.. 2.4 LO: other types of plots (3) [anoop] -.. ----------------------------------------- -.. * scatter -.. * pie chart -.. * bar chart -.. * log -.. * illustration of other plots, matplotlib help - -=================== -Other type of plots -=================== - -{{{ show the first slide }}} - -Hello and welcome to the tutorial other type of plots. - -{{{ show the outline slide }}} - -In this tutorial we will cover scatter plot, pie chart, bar chart and -log plot. We will also see few other plots and also introduce you to -the matplotlib help. - - -Let us start with scatter plot. - -{{{ switch to the next slide }}} - -In a scatter plot, the data is displayed as a collection of points, -each having the value of one variable determining the position on the -horizontal axis and the value of the other variable determining the -position on the vertical axis. This kind of plot is also called a -scatter chart, scatter diagram and scatter graph. - -Before we proceed further get your IPython interpreter running with -the ``-pylab`` option. Start your IPython interpreter as -:: - - ipython -pylab - -{{{ open the ipython interpreter in the terminal using the command -ipython -pylab }}} - -{{{ switch to the next slide having the problem statement of first -exercise }}} - -Now, let us plot a scatter plot showing the percentage profit of company A -from the year 2000-2010. The data for the same is available in the -file ``company-a-data.txt``. - -{{{ open the file company-a-data.txt and show the content }}} - -The data file has two lines with a set of values in each line, the -first line representing years and the second line representing the -profit percentages. - -{{{ close the file and switch to the terminal }}} - -To product the scatter plot first we need to load the data from the -file using ``loadtxt``. We learned in one of the previous sessions, -and it can be done as :: - - year,profit = loadtxt('/home/fossee/other-plot/company-a-data.txt',dtype=type(int())) - -Now in-order to generate the scatter graph we will use the function -``scatter()`` -:: - - scatter(year,profit) - -Notice that we passed two arguments to ``scatter()`` function, first -one the values in x-coordinate, year, and the other the values in -y-coordinate, the profit percentage. - -{{{ switch to the next slide which has the problem statement of -problem to be tried out }}} - -Now here is a question for you to try out, plot the same data with red -diamonds. - -**Clue** - *try scatter? in your ipython interpreter* - -.. scatter(year,profit,color='r',marker='d') - -Now let us move on to pie chart. - -{{{ switch to the slide which says about pie chart }}} - -A pie chart or a circle graph is a circular chart divided into -sectors, illustrating proportion. - -{{{ switch to the slide showing the problem statement of second -exercise question }}} - -Plot a pie chart representing the profit percentage of company A, with -the same data from file ``company-a-data.txt``. So let us reuse the -data we have loaded from the file previously. - -We can plot the pie chart using the function ``pie()``. -:: - - pie(profit,labels=year) - -Notice that we passed two arguments to the function ``pie()``. The -first one the values and the next one the set of labels to be used in -the pie chart. - -{{{ switch to the next slide which has the problem statement of -problem to be tried out }}} - -Now here is a question for you to try out, plot a pie chart with the -same data with colors for each wedges as white, red, black, magenta, -yellow, blue, green, cyan, yellow, magenta and blue respectively. - -**Clue** - *try pie? in your ipython interpreter* - -.. pie(t,labels=s,colors=('w','r','k','m','y','b','g','c','y','m','b')) - -{{{ switch to the slide which says about bar chart }}} - -Now let us move on to bar chart. A bar chart or bar graph is a chart -with rectangular bars with lengths proportional to the values that -they represent. - -{{{ switch to the slide showing the problem statement of third -exercise question }}} - -Plot a bar chart representing the profit percentage of company A, with -the same data from file ``company-a-data.txt``. - -So let us reuse the data we have loaded from the file previously. - -We can plot the bar chart using the function ``bar()``. -:: - - bar(year,profit) - -Note that the function ``bar()`` needs at least two arguments one the -values in x-coordinate and the other values in y-coordinate which is -used to determine the height of the bars. - -{{{ switch to the next slide which has the problem statement of -problem to be tried out }}} - -Now here is a question for you to try, plot a bar chart which is not -filled and which is hatched with 45\ :sup:`o` slanting lines as shown -in the image in the slide. - -**Clue** - *try bar? in your ipython interpreter* - -.. bar(year,profit,fill=False,hatch='/') - -{{{ switch to the slide which says about bar chart }}} - -Now let us move on to log-log plot. A log-log graph or log-log plot is -a two-dimensional graph of numerical data that uses logarithmic scales -on both the horizontal and vertical axes. Because of the nonlinear -scaling of the axes, a function of the form y = ax\ :sup:`b` will -appear as a straight line on a log-log graph - -{{{ switch to the slide showing the problem statement of fourth -exercise question }}} - - -Plot a `log-log` chart of y=5*x\ :sup:`3` for x from 1-20. - -Before we actually plot let us calculate the points needed for -that. And it could be done as, -:: - - x = linspace(1,20,100) - y = 5*x**3 - -Now we can plot the log-log chart using ``loglog()`` function, -:: - - loglog(x,y) - -To understand the difference between a normal ``plot`` and a ``log-log -plot`` let us create another plot using the function ``plot``. -:: - - figure(2) - plot(x,y) - -{{{ show both the plots side by side }}} - -So that was ``log-log() plot``. - -{{{ switch to the next slide which says: "How to get help on -matplotlib online"}}} - -Now we will see few more plots and also see how to access help of -matplotlib over the internet. - -Help about matplotlib can be obtained from -matplotlib.sourceforge.net/contents.html - -.. #[[Anoop: I am not so sure how to do the rest of it, so I guess we - can just browse through the side and tell them few. What is your - opinion??]] - -Now let us see few plots from -matplotlib.sourceforge.net/users/screenshots.html - -{{{ browse through the site quickly }}} - -{{{ switch to recap slide }}} - -Now we have come to the end of this tutorial. We have covered scatter -plot, pie chart, bar chart, log-log plot and also saw few other plots -and covered how to access the matplotlib online help. - -{{{ switch to the thank you slide }}} - -Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: diff -r e675f9208b91 -r 4054b1a6392d other_types_of_plots.rst --- a/other_types_of_plots.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,220 +0,0 @@ -.. 2.4 LO: other types of plots (3) [anoop] -.. ----------------------------------------- -.. * scatter -.. * pie chart -.. * bar chart -.. * log -.. * illustration of other plots, matplotlib help - -=================== -Other type of plots -=================== - -{{{ show the first slide }}} - -Hello and welcome to the tutorial other type of plots. - -{{{ show the outline slide }}} - -In this tutorial we will cover scatter plot, pie chart, bar chart and -log plot. We will also see few other plots and also introduce you to -the matplotlib help. - - -Let us start with scatter plot. - -{{{ switch to the next slide }}} - -In a scatter plot, the data is displayed as a collection of points, -each having the value of one variable determining the position on the -horizontal axis and the value of the other variable determining the -position on the vertical axis. This kind of plot is also called a -scatter chart, scatter diagram and scatter graph. - -Before we proceed further get your IPython interpreter running with -the ``-pylab`` option. Start your IPython interpreter as -:: - - ipython -pylab - -{{{ open the ipython interpreter in the terminal using the command -ipython -pylab }}} - -{{{ switch to the next slide having the problem statement of first -exercise }}} - -Now, let us plot a scatter plot showing the percentage profit of company A -from the year 2000-2010. The data for the same is available in the -file ``company-a-data.txt``. - -{{{ open the file company-a-data.txt and show the content }}} - -The data file has two lines with a set of values in each line, the -first line representing years and the second line representing the -profit percentages. - -{{{ close the file and switch to the terminal }}} - -To product the scatter plot first we need to load the data from the -file using ``loadtxt``. We learned in one of the previous sessions, -and it can be done as :: - - year,profit = loadtxt('/home/fossee/other-plot/company-a-data.txt',dtype=type(int())) - -Now in-order to generate the scatter graph we will use the function -``scatter()`` -:: - - scatter(year,profit) - -Notice that we passed two arguments to ``scatter()`` function, first -one the values in x-coordinate, year, and the other the values in -y-coordinate, the profit percentage. - -{{{ switch to the next slide which has the problem statement of -problem to be tried out }}} - -Now here is a question for you to try out, plot the same data with red -diamonds. - -**Clue** - *try scatter? in your ipython interpreter* - -.. scatter(year,profit,color='r',marker='d') - -Now let us move on to pie chart. - -{{{ switch to the slide which says about pie chart }}} - -A pie chart or a circle graph is a circular chart divided into -sectors, illustrating proportion. - -{{{ switch to the slide showing the problem statement of second -exercise question }}} - -Plot a pie chart representing the profit percentage of company A, with -the same data from file ``company-a-data.txt``. So let us reuse the -data we have loaded from the file previously. - -We can plot the pie chart using the function ``pie()``. -:: - - pie(profit,labels=year) - -Notice that we passed two arguments to the function ``pie()``. The -first one the values and the next one the set of labels to be used in -the pie chart. - -{{{ switch to the next slide which has the problem statement of -problem to be tried out }}} - -Now here is a question for you to try out, plot a pie chart with the -same data with colors for each wedges as white, red, black, magenta, -yellow, blue, green, cyan, yellow, magenta and blue respectively. - -**Clue** - *try pie? in your ipython interpreter* - -.. pie(t,labels=s,colors=('w','r','k','m','y','b','g','c','y','m','b')) - -{{{ switch to the slide which says about bar chart }}} - -Now let us move on to bar chart. A bar chart or bar graph is a chart -with rectangular bars with lengths proportional to the values that -they represent. - -{{{ switch to the slide showing the problem statement of third -exercise question }}} - -Plot a bar chart representing the profit percentage of company A, with -the same data from file ``company-a-data.txt``. - -So let us reuse the data we have loaded from the file previously. - -We can plot the bar chart using the function ``bar()``. -:: - - bar(year,profit) - -Note that the function ``bar()`` needs at least two arguments one the -values in x-coordinate and the other values in y-coordinate which is -used to determine the height of the bars. - -{{{ switch to the next slide which has the problem statement of -problem to be tried out }}} - -Now here is a question for you to try, plot a bar chart which is not -filled and which is hatched with 45\ :sup:`o` slanting lines as shown -in the image in the slide. - -**Clue** - *try bar? in your ipython interpreter* - -.. bar(year,profit,fill=False,hatch='/') - -{{{ switch to the slide which says about bar chart }}} - -Now let us move on to log-log plot. A log-log graph or log-log plot is -a two-dimensional graph of numerical data that uses logarithmic scales -on both the horizontal and vertical axes. Because of the nonlinear -scaling of the axes, a function of the form y = ax\ :sup:`b` will -appear as a straight line on a log-log graph - -{{{ switch to the slide showing the problem statement of fourth -exercise question }}} - - -Plot a `log-log` chart of y=5*x\ :sup:`3` for x from 1-20. - -Before we actually plot let us calculate the points needed for -that. And it could be done as, -:: - - x = linspace(1,20,100) - y = 5*x**3 - -Now we can plot the log-log chart using ``loglog()`` function, -:: - - loglog(x,y) - -To understand the difference between a normal ``plot`` and a ``log-log -plot`` let us create another plot using the function ``plot``. -:: - - figure(2) - plot(x,y) - -{{{ show both the plots side by side }}} - -So that was ``log-log() plot``. - -{{{ switch to the next slide which says: "How to get help on -matplotlib online"}}} - -Now we will see few more plots and also see how to access help of -matplotlib over the internet. - -Help about matplotlib can be obtained from -matplotlib.sourceforge.net/contents.html - -.. #[[Anoop: I am not so sure how to do the rest of it, so I guess we - can just browse through the side and tell them few. What is your - opinion??]] - -Now let us see few plots from -matplotlib.sourceforge.net/users/screenshots.html - -{{{ browse through the site quickly }}} - -{{{ switch to recap slide }}} - -Now we have come to the end of this tutorial. We have covered scatter -plot, pie chart, bar chart, log-log plot and also saw few other plots -and covered how to access the matplotlib online help. - -{{{ switch to the thank you slide }}} - -Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: diff -r e675f9208b91 -r 4054b1a6392d parsing_data.rst --- a/parsing_data.rst Wed Oct 13 17:32:23 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 e675f9208b91 -r 4054b1a6392d parsing_data/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parsing_data/questions.rst Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d parsing_data/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parsing_data/quickref.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d parsing_data/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parsing_data/script.rst Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d parsing_data/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parsing_data/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,84 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Parsing Data +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - What is meant by parsing data? + - String operations required for parsing + - Converting between data-types. +* Question 1 + Split the variable line using a space as argument. Is it same as + splitting without an argument ? +* Solution 1 + 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. +* Question 2 + What happens to the white space inside the sentence when it is + stripped? +* Solution 2 + #+begin_src python + In []: a_str = " white space " + In []: a_str.strip() + #+end_src +* Question 3 + What happens if you do =int("1.25")= +* Solution 3 + It raises an error since converting a float string into integer + directly is not possible. It involves an intermediate step of + converting to float. + #+begin_src python + In []: dcml_str = "1.25" + In []: flt = float(dcml_str) + In []: flt + In []: number = int(flt) + In []: number + #+end_src +* Summary + + 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 +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d parsing_data/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parsing_data/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,135 @@ +% Created 2010-10-10 Sun 18:28 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Parsing Data} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item What is meant by parsing data? +\item String operations required for parsing +\item Converting between data-types. +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Split the variable line using a space as argument. Is it same as + splitting without an argument ? +\end{frame} +\begin{frame} +\frametitle{Solution 1} +\label{sec-3} + + 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. +\end{frame} +\begin{frame} +\frametitle{Question 2} +\label{sec-4} + + What happens to the white space inside the sentence when it is + stripped? +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 2} +\label{sec-5} + +\lstset{language=Python} +\begin{lstlisting} +In []: a_str = " white space " +In []: a_str.strip() +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Question 3} +\label{sec-6} + + What happens if you do \texttt{int("1.25")} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 3} +\label{sec-7} + + It raises an error since converting a float string into integer + directly is not possible. It involves an intermediate step of + converting to float. +\lstset{language=Python} +\begin{lstlisting} +In []: dcml_str = "1.25" +In []: flt = float(dcml_str) +In []: flt +In []: number = int(flt) +In []: number +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-8} + +\begin{itemize} +\item How to tokenize a string using various delimiters +\item How to get rid of extra white space around +\item How to convert from one type to another +\item How to parse input data and perform computations on it +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-9} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d plotting_using_sage/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting_using_sage/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,70 @@ +Objective Questions +------------------- + + 1. Plot the curve ``sin(x) - cos(x)`` in the range (0, 2pi) + + Answer:: + + x = var('x') + plot(sin(x) - cos(x), (x, 0, 2*pi)) + + 2. plot ``sin(3x)`` and ``cos(x/3)`` and show them in same figure + + Answer:: + + x = var('x') + p1 = plot(sin(3*x), (x, 0, 2*pi)) + p2 = plot(cos(x/3), (x, 0, 2*pi)) + show(p1+p2) + + 3. plot ``cos(x)`` vs ``sin(x)^15`` in the range (-2pi, 2pi) + + Answer:: + + x = var('x') + parametric_plot((cos(x), sin(x)^15), (x, -2*pi, 2*pi)) + + 4. plot tan curve in the range (-2pi, 2pi) in red colour. + [hint: see the documentation] + + Answer:: + + x = var('x') + p1 = plot(tan(x), (x, -2*pi, 2*pi), color=(1, 0, 0)) + show(p1) + + 5. plot ``e^(1/x^2)`` in the range (0.5, 2.5) and set the y-axis limits to (0, + 20) + + Answer:: + + x = var('x') + p2 = plot(e^(1/x^2), (x, 0.5, 2.5)) + show(p2, ymin=0, ymax=20) + + 6. plot the function ``y = 5x + 3`` using dotted line in the range (-2, 2) + [hint: read the documentation of the function ``line``] + + Answer:: + + points = [ (i, 5*i+3) for i in srange(-2,2,0.1) ] + l1 = line(points, linestyle=":") + show(l1) + + 7. plot the function ``z = cos(x) + sin(y)`` for x in the range (0, 2pi) and y + in range (-2pi, 2pi) + + Answer:: + + x, y = var('x y') + plot3d(cos(x) + sin(y), (x, 0, 2*pi), (y, -2*pi, 2*pi)) + + 8. Read the sage documentation and find out which function plots closed surfaces + + a. parametric_plot3d + #. plot3d + #. implicit_plot3d + #. contour_plot + + Answer: implicit_plot3d + diff -r e675f9208b91 -r 4054b1a6392d plotting_using_sage/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting_using_sage/quickref.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d plotting_using_sage/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting_using_sage/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,257 @@ +.. 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, welcome to the tutorial on "Plotting using SAGE". + +{{{ Show the outline slide }}} + +In this tutorial we shall look at + + * 2D plotting in SAGE + * 3D plotting in SAGE + +We shall first create a symbolic variable ``x`` +:: + + x = var('x') + +We shall plot the function ``sin(x) - cos(x) ^ 2`` in the range (-5, 5). +:: + + plot(sin(x) - cos(x) ^ 2, (x, -5, 5)) + +As we can see, the plot is shown. + +``plot`` command takes the symbolic function as the first argument and the +range as the second argument. + +{{{ Pause here and try out the following exercises }}} + +%% 1 %% Define a variable ``y`` and plot the function ``y^2 + 5y - 7`` in the + range (-3, 3) + +{{{ continue from paused state }}} + +:: + + y = var('y') + plot(y^2 + 5*y -7, (y, -3, 3)) + +We have seen that plot command plots the given function on a linear range. + +What if the x and y values are functions of another variable. +For instance, lets plot the trajectory of a projectile. + +A projectile was thrown at 50 m/s^2 and at an angle of 45 degrees from the +ground. We shall plot the trajectory of the particle for 5 seconds. + +These types of plots can be drawn using the parametric_plot function. +We first define the time variable. +:: + + t = var('t') + +Then we define the x and y as functions of t. +:: + + f_x = 50 * cos(pi/4) + f_y = 50 * sin(pi/4) * t - 1/2 * 9.81 * t^2 ) + +We then call the ``parametric_plot`` function as +:: + + parametric_plot((f_x, f_y), (t, 0, 5)) + +And we can see the trajectory of the projectile. + +The ``parametric_plot`` funciton takes a tuple of two functions as the first +argument and the range over which the independent variable varies as the second +argument. + +{{{ Pause here and try out the following exercises }}} + +%% 2 %% A particle is thrown into the air at 10 m/s^2 and at angle of 60 degrees + from the top of a 100 m tower. Plot the trajectory of the particle. + +{{{ continue from paused state }}} + +:: + + t = var('t') + f_x = 10 * cos(pi/3) * t + f_y = 100 + 10 * sin(pi/3) * t - 1/2 * 9.81 * t^2 + parametric_plot((f_x, f_y), (t,0,5)) + +Now we shall look at how to plot a set of points. + +We have the ``line`` function to acheive this. + +We shall plot sin(x) at few points and join them. + +First we need the set of points. +:: + + points = [ (x, sin(x)) for x in srange(-2*float(pi), 2*float(pi), 0.75) ] + +``srange`` takes a start, a stop and a step argument and returns a list of +point. We generate list of tuples in which the first value is ``x`` and second +is ``sin(x)``. + +:: + + line(points) + +plots the points and joins them with a line. + +{{{ Pause here and try out the following exercises }}} + +%% 3 %% Plot the cosine function using line function. + +{{{ continue from paused state }}} + +:: + + points = [ (x, cos(x)) for x in srange(-2*float(pi), 2*float(pi), 0.75) ] + line(points) + +The ``line`` function behaves like the plot command in matplotlib. The +difference is that ``plot`` command takes two sequences while line command +expects a sequence of co-ordinates. + +As we can see, the axes limits are set by SAGE. Often we would want to set them +ourselves. Moreover, the plot is shown here since the last command that is +executed produces a plot. + +Let us try this example +:: + + plot(cos(x), (x,0,2*pi)) + # Does the plot show up?? + +As we can see here, the plot is not shown since the last command does not +produce a plot. + +The actual way of showing a plot is to use the ``show`` command. + +:: + + p1 = plot(cos(x), (x,0,2*pi)) + show(p1) + # What happens now?? + +As we can see the plot is shown since we used it with ``show`` command. + +``show`` command is also used set the axes limits. + +:: + + p1 = plot(cos(x), (x,0,2*pi)) + show(p1, xmin=0, xmax=2*pi, ymin=-1.2, ymax=1.2) + +As we can see, we just have to pass the right keyword arguments to the ``show`` +command to set the axes limits. + +{{{ Pause here and try out the following exercises }}} + +%% 4 %% Plot the cosine function in the range (-2pi, 2pi) and set the x-axis + limits to (-5, 5) and y-axis limits to (-2, 2) respectively. + +{{{ continue from paused state }}} + +:: + + p1 = plot(cos(x), (x, 0, 2*pi)) + show(p1, xmin=-5, xmax=5, ymin=-2, ymax=2) + +The ``show`` command can also be used to show multiple plots. +:: + + p1 = plot(cos(x), (x, 0, 2*pi)) + p2 = plot(sin(x), (x, 0, 2*pi)) + show(p1+p2) + +As we can see, we can add the plots and use them in the ``show`` command. + +{{{ Pause here and try out the following exercises }}} + +%% 5 %% Plot sin(x) and sin(2*x) in the range (0, 2pi) + +{{{ continue from paused state }}} + +:: + + p1 = plot(sin(x), (x, 0, 2*pi)) + p2 = plot(sin(2*x), (x, 0, 2*pi)) + show(p1+p2) + +Now we shall look at 3D plotting in SAGE. + +We have the ``plot3d`` function that takes a function in terms of two +independent variables and the range over which they vary. + +:: + + x, y = var('x y') + plot3d(x^2 + y^2, (x, 0, 2), (y, 0, 2)) + +We get a 3D plot which can be rotated and zoomed using the mouse. + +{{{ Pause here and try out the following exercises }}} + +%% 6 %% Plot the function sin(x)^2 + cos(y)^2 for x in range (0,2) and y in + range (-2, 2) + +{{{ continue from paused state }}} + +:: + + x, y = var("x y") + plot3d( sin(x)^2 + cos(y)^2, (x, 0, 2), (y, -2, 2)) + +``parametric_plot3d`` function plots the surface in which x, y and z are +functions of another variable. + +:: + + u, v = var("u v") + f_x = u + f_y = v + f_z = u^2 + v^2 + parametric_plot3d((f_x, f_y, f_z), (u, 0, 2), (v, 0, 2)) + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have learnt + + * How to draw 2D plots using plot comand + * How to use the parametric_plot and line functions + * How to use show command for multiple plots and setting axes limits + * How to draw 3D plots + +{{{ 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 e675f9208b91 -r 4054b1a6392d plotting_using_sage/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/plotting_using_sage/slides.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d progress.org --- a/progress.org Wed Oct 13 17:32:23 2010 +0530 +++ b/progress.org Wed Oct 13 17:32:59 2010 +0530 @@ -1,55 +1,55 @@ -| S.No | Name | Units | Author | 1st Review (Status) | 2nd Review (Status) | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 1.2 LO: | getting started with =ipython= | 2 | Punch | | | -| 1.3 LO: | using the =plot= command interactively | 2 | Amit | Anoop (Pending) | Puneeth (Pending) | -| 1.4 LO: | embellishing a plot | 2 | Nishanth | Anoop (Done) | Madhu (Done) | -| 1.5 LO: | saving plots | 2 | Anoop | | | -| 1.6 LO: | multiple plots | 3 | Madhu | Nishanth (Done) | Punch (Pending) | -| 1.7 LO: | additional features of IPython | 2 | Nishanth | Amit (Pending) | Madhu (Pending) | -| 1.8 LO: | module level assessment | 3 | Madhu | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 2.2 LO: | loading data from files | 3 | Punch | Nishanth (Done) | Anoop (Pending) | -| 2.3 LO: | plotting the data | 3 | Amit | Anoop (Pending) | Punch (Pending) | -| 2.4 LO: | other types of plots | 3 | Anoop | | | -| 2.5 LO: | module level assessment | 3 | Nishanth | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 3.1 LO: | getting started with lists | 2 | Amit | Madhu (Pending) | Nishanth (Done) | -| 3.2 LO: | getting started with =for= | 2 | Anoop | Nishanth (Done) | Amit (Done) | -| 3.3 LO: | getting started with strings | 2 | Madhu | | | -| 3.4 LO: | getting started with files | 3 | Punch | | | -| 3.5 LO: | parsing data | 3 | Nishanth | Amit (Done) | Punch (Pending) | -| 3.6 LO: | statistics | 2 | Amit | Anoop (Pending) | Puneeth (Pending) | -| 3.7 LO: | module level assessment | 3 | Madhu | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 4.1 LO: | getting started with arrays | 2 | Anoop | | | -| 4.2 LO: | accessing parts of arrays | 4 | Punch | | | -| 4.3 LO: | Matrices | 3 | Anoop | | | -| 4.4 LO: | Least square fit | 2 | Nishanth | Punch (Pending) | Anoop (Pending) | -| 4.5 LO: | Assessment | 3 | Punch | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 5.1 LO: | getting started with sage notebook | 3 | Madhu | | | -| 5.2 LO: | getting started with symbolics | 3 | Amit | Madhu (Pending) | Nishanth (Pending) | -| 5.3 LO: | using Sage | 4 | Punch | | | -| 5.4 LO: | using sage to teach | 3 | Nishanth | | | -| 5.5 LO: | Assessment | 3 | Anoop | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 6.1 LO: | basic datatypes & operators | 4 | Amit | Madhu (Pending) | Nishanth (Done) | -| 6.2 LO: | I/O | 1 | Nishanth | | | -| 6.3 LO: | conditionals | 2 | Madhu | | | -| 6.4 LO: | loops | 2 | Puneeth | | | -| 6.5 LO: | Assessment | 3 | Anoop | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 7.1 LO: | manipulating lists | 3 | Madhu | | | -| 7.2 LO: | manipulating strings | 2 | Punch | | | -| 7.3 LO: | getting started with tuples | 2 | Nishanth | | | -| 7.4 LO: | dictionaries | 2 | Anoop | | | -| 7.5 LO: | sets | 2 | Nishanth | | | -| 7.6 LO: | Assessment | 3 | Amit | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| -| 8.1 LO: | getting started with functions | 3 | Nishanth | | | -| 8.2 LO: | advanced features of functions | 3 | Punch | | | -| 8.3 LO: | using python modules | 3 | Anoop | | | -| 8.4 LO: | writing python scripts | 2 | Nishanth | | | -| 8.5 LO: | testing and debugging | 2 | Amit | | | -| 8.6 LO: | Assessment | 3 | Madhu | | | -|---------+----------------------------------------+-------+----------+---------------------+---------------------| +| S.No | Name | Units | Author | Review | Checklist | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 1.2 LO: | getting started with =ipython= | 2 | Punch | | | +| 1.3 LO: | using the =plot= command interactively | 2 | Amit | Anoop (Pending) | | +| 1.4 LO: | embellishing a plot | 2 | Nishanth | Anoop (Done) | | +| 1.5 LO: | saving plots | 2 | Anoop | | | +| 1.6 LO: | multiple plots | 3 | Madhu | Nishanth (Done) | | +| 1.7 LO: | additional features of IPython | 2 | Nishanth | Amit (Pending) | | +| 1.8 LO: | module level assessment | 3 | Madhu | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 2.2 LO: | loading data from files | 3 | Punch | Nishanth (Done) | | +| 2.3 LO: | plotting the data | 3 | Amit | Anoop (Pending) | | +| 2.4 LO: | other types of plots | 3 | Anoop | | | +| 2.5 LO: | module level assessment | 3 | Nishanth | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 3.1 LO: | getting started with lists | 2 | Amit | Madhu (Pending) | | +| 3.2 LO: | getting started with =for= | 2 | Anoop | Nishanth (Done) | | +| 3.3 LO: | getting started with strings | 2 | Madhu | | | +| 3.4 LO: | getting started with files | 3 | Punch | | | +| 3.5 LO: | parsing data | 3 | Nishanth | Amit (Done) | | +| 3.6 LO: | statistics | 2 | Amit | Anoop (Pending) | | +| 3.7 LO: | module level assessment | 3 | Madhu | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 4.1 LO: | getting started with arrays | 2 | Anoop | Punch (Done) | | +| 4.2 LO: | accessing parts of arrays | 4 | Punch | | | +| 4.3 LO: | Matrices | 3 | Anoop | | | +| 4.4 LO: | Least square fit | 2 | Nishanth | Punch (Pending) | | +| 4.5 LO: | Assessment | 3 | Punch | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 5.1 LO: | getting started with sage notebook | 3 | Madhu | | | +| 5.2 LO: | getting started with symbolics | 3 | Amit | Madhu (Pending) | | +| 5.3 LO: | using Sage | 4 | Punch | | | +| 5.4 LO: | using sage to teach | 3 | Nishanth | | | +| 5.5 LO: | Assessment | 3 | Anoop | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 6.1 LO: | basic datatypes & operators | 4 | Amit | Madhu (Pending) | | +| 6.2 LO: | I/O | 1 | Nishanth | | | +| 6.3 LO: | conditionals | 2 | Madhu | | | +| 6.4 LO: | loops | 2 | Puneeth | | | +| 6.5 LO: | Assessment | 3 | Anoop | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 7.1 LO: | manipulating lists | 3 | Madhu | | | +| 7.2 LO: | manipulating strings | 2 | Punch | | | +| 7.3 LO: | getting started with tuples | 2 | Nishanth | | | +| 7.4 LO: | dictionaries | 2 | Anoop | | | +| 7.5 LO: | sets | 2 | Nishanth | | | +| 7.6 LO: | Assessment | 3 | Amit | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| +| 8.1 LO: | getting started with functions | 3 | Nishanth | | | +| 8.2 LO: | advanced features of functions | 3 | Punch | | | +| 8.3 LO: | using python modules | 3 | Anoop | | | +| 8.4 LO: | writing python scripts | 2 | Nishanth | | | +| 8.5 LO: | testing and debugging | 2 | Amit | | | +| 8.6 LO: | Assessment | 3 | Madhu | | | +|---------+----------------------------------------+-------+----------+-----------------+-----------| diff -r e675f9208b91 -r 4054b1a6392d savefig.rst --- a/savefig.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,111 +0,0 @@ -======= -Savefig -======= - -Hello and welcome to the tutorial. In this tutorial you will learn how -to save plots using Python. - -Start your IPython interpreter with the command :: - - ipython -pylab - -It will start your IPython interpreter with the required python -modules for plotting and saving your plots. - -{{{ Open ipython }}} - -Now let us plot something, let us plot a sine wave from minus 3 pi to -3 pi. Let us start by calculating the required points for the plot. It -can be done using linspace as, :: - - x = linspace(-3*pi,3*pi,100) - -We have stored required points in x. Now let us plot the points using -the statement :: - - plot(x,sin(x)) - -{{{ Keep the plot open }}} - -Done! we have made a very basic sine plot, now let us see how to save -the plot for future use so that you can embed the plot in your -reports. - -{{{ Switch the focus to IPython interpreter window }}} - -For saving the plot, we will use savefig function, and it has to be -done with the plot window open. The statement is, :: - - savefig('/home/fossee/sine.png') - -Notice that ``savefig`` function takes one argument which is a string -which is the filename. The last 3 characters after the ``.`` in the -filename is the extension or type of the file which determines the -format in which you want to save. - -{{{ Highlight the /home/fossee part using mouse movements }}} - -Also, note that we gave the full path or the absolute path to which we -want to save the file. - -{{{ Highlight the .png part using mouse movements }}} - -Here I have used an extension ``.png`` which means i want to save the -image as a PNG file. - -Now let us locate ``sine.png`` file saved. We saved the file to -``/home/fossee`` so let us navigate to ``/home/fossee`` using the -file browser. - -{{{ Open the browser, navigate to /home/fossee and highlight the file -sine.png }}} - -Yes, the file ``sine.png`` is here and let us check the it. - -{{{ Open the file sine.png and show it for two-three seconds and then -close it and return to IPython interpreter, make sure the plot window -is still open, also don't close the file browser window }}} - -So in-order to save a plot, we use ``savefig`` function. ``savefig`` -can save the plot in many formats, such as pdf - portable document -format, ps - post script, eps - encapsulated post script, svg - -scalable vector graphics, png - portable network graphics which -support transparency etc. - -#[slide must give the extensions for the files - Anoop] - -Let us now try to save the plot in eps format. ``eps`` stands for -encapsulated post script, and it can be embedded in your latex -documents. - -{{{ Switch focus to the already open plot window }}} - -We still have the old sine plot with us, and now let us save the plot -as ``sine.eps``. - -{{{ Switch focus to IPython interpreter }}} - -Now, We will save the plot using the function ``savefig`` :: - - savefig('/home/fossee/sine.eps') - -{{{ Switch focus to file browser window }}} - -Now let us go to ``/home/fossee`` and see the new file created. - -{{{ Highlight the file sine.eps with a single mouse click for 2 -seconds and then double click and open the file }}} - -Yes! the new file ``sine.eps`` is here. - -Now you may try saving the same in pdf, ps, svg formats. - -Let us review what we have learned in this session! We have learned to -save plots in different formats using the function ``savefig()``. - -Thank you! - -.. Author: Anoop Jacob Thomas - Reviewer 1: - Reviewer 2: - External reviewer: diff -r e675f9208b91 -r 4054b1a6392d savefig/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/savefig/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,118 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + + +1. What argument can be used with savefig to increase the resolution + of the plot while saving a plot. + + a. fname + #. transparency + #. dpi + #. format + +Answer: dpi + +2. The fname argument of savefig has to be always absolute path. + + a. True + #. False + +Answer: False + +3. You are right now in the directory `/home/fossee`, from the + following which one is the correct one in-order to save the plot as + svg with the filename `plot` to the directory `/home/fossee/sine/` + + a. savefig('/sine/plot.svg') + #. savefig('sine/plot.svg') + #. savefig('home/fossee/sine/plot.svg') + #. All of these + #. None of the above + +Answer: savefig('sine/plot.svg') + +4. Which is the best image format to be used with Latex documents + which savefig supports? + + a. SVG - Scalable Vector Graphics + #. EPS - Encapsulated Post Script + #. PS - Post Script + #. PNG - Portable Network Graphics + #. None of the above + +Answer: EPS - Encapsulated Post Script + +5. ``savefig('sine.png')`` saves the plot in, + + a. The root directory ``/`` (on GNU/Linux, Unix based systems) + ``c:\`` (on windows). + #. Will result in an error as full path is not supplied. + #. The current working directory. + #. Predefined directory like ``/documents``. + +Answer: The current working directory. + +6. Study the following code and tell what will happen, + :: + savefig('cosine.png',facecolor='blue') + + a. Will generate an error as plot statements are missing + #. Will generate an error as full path is not specified + #. Create a file ``cosine.png`` with blue background at the current + working directory. + #. Create a file ``cosine.png`` with blue background at a + predefined directory like ``/documents``. + +Answer: Create a file ``cosine.png`` with blue background at the + current working directory. + +7. How to save the below plot as ``sine_green_border.png`` with green + color border/edge in the current working directory. The plot is given + as, + :: + x = linspace(-5*pi,5*pi,200) + plot(x,sin(x),linewidth=2) + legend(['sin(x)']) + + a. ``savefig('sine_green_border.png',bordercolor='green')`` + #. ``savefig('sine_green_border.png',facecolor='green')`` + #. ``savefig('sine_green_border.png',edgecolor='green')`` + #. ``savefig('/sine_green_border.png',bordercolor='green')`` + +Answer: savefig('sine_green_border.png',edgecolor='green') + +8. Given the below code snippet, what does it do? + :: + x = linspace(-5*pi,5*pi,200) + plot(x,sin(x),linewidth=2) + legend(['sin(x)']) + savefig('sine.png',format='pdf',papertype='a4') + + a. Save the sine plot in file sine.png as a pdf file in page-size + A4 and saves it into the current working directory + #. Save the sine plot in file sine.png.pdf in page-size A4 into the + current working directory. + #. Save the sine plot in a file sine.png in png format with + page-size A4 in the current working directory overriding the + format argument + #. Error in filename and format mismatch. + +Answer: Save the sine plot in file sine.png as a pdf file in page-size + A4 and saves it into the current working directory + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Plot a cosine plot from -2pi to 2pi in green color taking 300 + points. Title the plot as 'Cosine plot' and the legend plot with + 'cos(x)'. And save the plot as a pdf file with the filename + cosine_plot. + +2. Plot tan(x) where x varies from -4pi to 4pi in red color taking 600 + points. Title the plot as 'Tan plot' and the legend plot with + 'tan(x)'. And save the plot as a svg file with the filename + tangent_plot. diff -r e675f9208b91 -r 4054b1a6392d savefig/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/savefig/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,151 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Saving plots using ``savefig()`` function. +.. #. Saving plots in different formats. + + +.. Prerequisites +.. ------------- + +.. 1. should have ``ipython`` and ``pylab`` installed. +.. #. getting started with ``ipython``. +.. #. using plot command interactively. + +.. Author : Anoop Jacob Thomas + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + + +======= +Savefig +======= + +{{{ Show the first slide }}} + +Hello and welcome to the tutorial saving plots. + +{{{ switch to next slide, outline slide }}} + +In this tutorial you will learn how to save plots using Python. And +saving in different formats, and locating the file in the file system. + +{{{ switch to next slide, a sine wave}}} + +Start your IPython interpreter with the command :: + + ipython -pylab + +It will start your IPython interpreter with the required python +modules for plotting and saving your plots. + +{{{ Open ipython }}} + +Now let us plot something, let us plot a sine wave from minus 3 pi to +3 pi. Let us start by calculating the required points for the plot. It +can be done using linspace as, :: + + x = linspace(-3*pi,3*pi,100) + +We have stored required points in x. Now let us plot the points using +the statement :: + + plot(x,sin(x)) + +{{{ Keep the plot open }}} + +Done! we have made a very basic sine plot, now let us see how to save +the plot for future use so that you can embed the plot in your +reports. + +{{{ switch to next slide, savefig() }}} + +{{{ Switch the focus to IPython interpreter window }}} + +For saving the plot, we will use ``savefig()`` function, and it has to be +done with the plot window open. The statement is, :: + + savefig('/home/fossee/sine.png') + +Notice that ``savefig`` function takes one argument which is a string +which is the filename. The last 3 characters after the ``.`` in the +filename is the extension or type of the file which determines the +format in which you want to save. + +{{{ Highlight the /home/fossee part using mouse movements }}} + +Also, note that we gave the full path or the absolute path to which we +want to save the file. + +{{{ Highlight the .png part using mouse movements }}} + +Here I have used an extension ``.png`` which means i want to save the +image as a PNG file. + +Now let us locate ``sine.png`` file saved. We saved the file to +``/home/fossee`` so let us navigate to ``/home/fossee`` using the +file browser. + +{{{ Open the browser, navigate to /home/fossee and highlight the file +sine.png }}} + +Yes, the file ``sine.png`` is here and let us check it. + +{{{ Open the file sine.png and show it for two-three seconds and then +close it and return to IPython interpreter, make sure the plot window +is still open, also don't close the file browser window }}} + +{{{ switch to next slide, More on savefig() }}} + +So in-order to save a plot, we use ``savefig`` function. ``savefig`` +can save the plot in many formats, such as pdf - portable document +format, ps - post script, eps - encapsulated post script, svg - +scalable vector graphics, png - portable network graphics which +support transparency etc. + +.. #[[slide must give the extensions for the files - Anoop]] + +{{{ switch to next slide, exercise 1 }}} + +Let us now try to save the plot in eps format. ``eps`` stands for +encapsulated post script, and it can be embedded in your latex +documents. Pause here and try to figure it out yourself. + +{{{ Switch focus to the already open plot window }}} + +We still have the sine plot with us, and now let us save the plot as +``sine.eps``. + +{{{ switch to next slide, solution 1 }}} + +{{{ Switch focus to IPython interpreter }}} + +Now, We will save the plot using the function ``savefig`` :: + + savefig('/home/fossee/sine.eps') + +{{{ Switch focus to file browser window }}} + +Now let us go to ``/home/fossee`` and see the new file created. + +{{{ Highlight the file sine.eps with a single mouse click for 2 +seconds and then double click and open the file }}} + +Yes! the new file ``sine.eps`` is here. + +{{{ switch to next slide, exercise 2 }}} + +Now you may try saving the same in pdf, ps, svg formats. + +{{{ Switch to summary slide }}} + +This brings us to the end of this tutorial, in this tutorial we +learned to save plots using the function ``savefig()``. Saving the +plots in different formats and locating the files in the file system. + +{{{ switch to Thank you slide }}} + +Thank you! diff -r e675f9208b91 -r 4054b1a6392d savefig/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/savefig/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,99 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Savefig +#+AUTHOR: FOSSEE +#+EMAIL: info@fossee.in +#+DATE: 2010-10-11 Mon + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Saving plots. + - Plotting in different formats. + - Locating the file in the file system. + +* Creating a basic plot + Plot a sine wave from -3pi to 3pi. + #+begin_src python + In []: x = linspace(-3*pi,3*pi,100) + + In []: plot(x, sin(x)) + #+end_src +* savefig() +** savefig() - to save plots + : syntax: savefig(fname) +** example +*** savefig('/home/fossee/sine.png') + - file sine.png saved to the folder /home/fossee + - .png - file type + +* More on savefig() +** Recall + - .png - file type +** File types supported +*** .pdf - PDF(Portable Document Format) +*** .ps - PS(Post Script) +*** .eps - Encapsulated Post Script + ~to be used with~ LaTeX ~documents~ +*** .svg - Scalable Vector Graphics + ~vector graphics~ +*** .png - Portable Network Graphics + ~supports transparency~ +* Exercise 1 + Save the sine plot in the format EPS which can be embedded in LaTeX documents. +* Solution 1 + #+begin_src python + savefig('/home/fossee/sine.eps') + #+end_src +* Exercise 2 + Save the sine plot in PDF, PS and SVG formats. + +* Summary + You should now be able to + - Use ~savefig()~ function + - Save plots in different formats + - PDF + - PS + - PNG + - SVG + - EPS + - Locating the files in file system. + +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d savefig/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/savefig/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,185 @@ +% Created 2010-10-11 Mon 17:08 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Savefig} +\author{FOSSEE} +\date{2010-10-11 Mon} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Saving plots. +\item Plotting in different formats. +\item Locating the file in the file system. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Creating a basic plot} +\label{sec-2} + + Plot a sine wave from -3pi to 3pi. +\begin{verbatim} +In []: x = linspace(-3*pi,3*pi,100) + +In []: plot(x, sin(x)) +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{savefig()} +\label{sec-3} +\begin{itemize} + +\item savefig() - to save plots +\label{sec-3_1}% +\begin{verbatim} + syntax: savefig(fname) +\end{verbatim} + + +\item example +\label{sec-3_2}% +\begin{itemize} + +\item savefig('/home/fossee/sine.png') +\label{sec-3_2_1}% +\begin{itemize} +\item file sine.png saved to the folder /home/fossee +\item .png - file type +\end{itemize} + + +\end{itemize} % ends low level +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{More on savefig()} +\label{sec-4} +\begin{itemize} + +\item Recall +\label{sec-4_1}% +\begin{itemize} +\item .png - file type +\end{itemize} + + +\item File types supported +\label{sec-4_2}% +\begin{itemize} + +\item .pdf - PDF(Portable Document Format)\\ +\label{sec-4_2_1}% +\item .ps - PS(Post Script)\\ +\label{sec-4_2_2}% +\item .eps - Encapsulated Post Script\\ +\label{sec-4_2_3}% +\texttt{to be used with} \LaTeX{} \texttt{documents} + +\item .svg - Scalable Vector Graphics\\ +\label{sec-4_2_4}% +\texttt{vector graphics} + +\item .png - Portable Network Graphics\\ +\label{sec-4_2_5}% +\texttt{supports transparency} +\end{itemize} % ends low level +\end{itemize} % ends low level +\end{frame} +\begin{frame} +\frametitle{Exercise 1} +\label{sec-5} + + Save the sine plot in the format EPS which can be embedded in \LaTeX{} documents. +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-6} + +\begin{verbatim} +savefig('/home/fossee/sine.eps') +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Exercise 2} +\label{sec-7} + + Save the sine plot in PDF, PS and SVG formats. +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-8} + + You should now be able to +\begin{itemize} +\item Use \texttt{savefig()} function +\item Save plots in different formats + +\begin{itemize} +\item PDF +\item PS +\item PNG +\item SVG +\item EPS +\end{itemize} + +\item Locating the files in file system. +\end{itemize} + + +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-9} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d sets.rst --- a/sets.rst Wed Oct 13 17:32:23 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 e675f9208b91 -r 4054b1a6392d sets/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sets/questions.rst Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d sets/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sets/quickref.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d sets/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sets/script.rst Wed Oct 13 17:32:59 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 symmetric 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. +Thank you! + diff -r e675f9208b91 -r 4054b1a6392d sets/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sets/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,71 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Sets +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Defining Sets + - Operations on sets + +* Question 1 + Given a list of marks, ~marks = [20, 23, 22, 23, 20, 21, 23]~ list + all the duplicates +* Solution 1 + #+begin_src python + 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) + #+end_src +* Summary + You should now be able to -- + + make sets from lists + + input sets directly + + perform operations like union, intersection, symmetric difference + + check if a subset of another + + check containership, length and other properties similar to lists +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d sets/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/sets/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,104 @@ +% Created 2010-10-10 Sun 23:53 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Sets} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Defining Sets +\item Operations on sets +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Given a list of marks, \texttt{marks = [20, 23, 22, 23, 20, 21, 23]} list + all the duplicates +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +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) +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-4} + + You should now be able to -- +\begin{itemize} +\item make sets from lists +\item input sets directly +\item perform operations like union, intersection, symmetric difference +\item check if a subset of another +\item check containership, length and other properties similar to lists +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-5} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d template/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/template/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,123 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Accessing parts of arrays +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Manipulating one and multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slicing and striding on arrays to access chunks + - Read images into arrays and manipulations +* Sample Arrays + #+begin_src python + In []: A = array([12, 23, 34, 45, 56]) + + In []: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) + + #+end_src +* Question 1 + Change the last column of ~C~ to zeroes. +* Solution 1 + #+begin_src python + In []: C[:, -1] = 0 + #+end_src +* Question 2 + Change ~A~ to ~[11, 12, 13, 14, 15]~. +* Solution 2 + #+begin_src python + In []: A[:] = [11, 12, 13, 14, 15] + #+end_src +* squares.png + #+begin_latex + \begin{center} + \includegraphics[scale=0.6]{squares} + \end{center} + #+end_latex +* Question 3 + - obtain ~[22, 23]~ from ~C~. + - obtain ~[11, 21, 31, 41]~ from ~C~. + - obtain ~[21, 31, 41, 0]~. +* Solution 3 + #+begin_src python + In []: C[1, 1:3] + In []: C[0:4, 0] + In []: C[1:5, 0] + #+end_src +* Question 4 + Obtain ~[[23, 24], [33, -34]]~ from ~C~ +* Solution 4 + #+begin_src python + In []: C[1:3, 2:4] + #+end_src +* Question 5 + Obtain the square in the center of the image +* Solution 5 + #+begin_src python + In []: imshow(I[75:225, 75:225]) + #+end_src +* Question 6 + Obtain the following + #+begin_src python + [[12, 0], [42, 0]] + [[12, 13, 14], [0, 0, 0]] + #+end_src + +* Solution 6 + #+begin_src python + In []: C[::3, 1::3] + In []: C[::4, 1:4] + #+end_src +* Summary + You should now be able to -- + - Manipulate 1D \& Multi dimensional arrays + - Access and change individual elements + - Access and change rows and columns + - Slice and stride on arrays + - Read images into arrays and manipulate them. +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d tuples.rst --- a/tuples.rst Wed Oct 13 17:32:23 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 e675f9208b91 -r 4054b1a6392d tuples/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tuples/questions.rst Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d tuples/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tuples/quickref.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d tuples/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tuples/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,173 @@ +.. Objectives +.. ---------- + +.. A - Students and teachers from Science and engineering backgrounds + B - Will learn what are tuples and why they are needed + Will learn the various methods of accessing elements in tuples + C - + D - + +.. #. what are tuples +.. #. comparison with lists +.. #. why are they needed + + +.. 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 e675f9208b91 -r 4054b1a6392d tuples/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tuples/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,69 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Getting started -- Tuples +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - what are tuples + - comparison with lists + - why are they needed +* Question 1 + ~a = 5~ and ~b = 7~. swap the values of ~a~ and ~b~ +* Solution 1 + #+begin_src python + temp = a + a = b + b = temp + + a + b + #+end_src +* Summary + You should now -- + + Be able to define tuples + + Know the similarities with lists, like -- indexing and iterability + + Know about the immutability of tuples + + Be able to swap variables in the Pythonic way + + Know about packing and unpacking of tuples +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d tuples/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tuples/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,103 @@ +% Created 2010-10-10 Sun 23:03 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Getting started -- Tuples} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item what are tuples +\item comparison with lists +\item why are they needed +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + \texttt{a = 5} and \texttt{b = 7}. swap the values of \texttt{a} and \texttt{b} +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +temp = a +a = b +b = temp + +a +b +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-4} + + You should now -- +\begin{itemize} +\item Be able to define tuples +\item Know the similarities with lists, like -- indexing and iterability +\item Know about the immutability of tuples +\item Be able to swap variables in the Pythonic way +\item Know about packing and unpacking of tuples +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-5} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d using python modules/four_plot.png Binary file using python modules/four_plot.png has changed diff -r e675f9208b91 -r 4054b1a6392d using python modules/four_plot.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/four_plot.py Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,11 @@ +x=linspace(-5*pi, 5*pi, 500) +plot(x, x, 'b') +plot(x, -x, 'b') +plot(x, sin(x), 'g', linewidth=2) +plot(x, x*sin(x), 'r', linewidth=3) +legend(['x', '-x', 'sin(x)', 'xsin(x)']) +annotate('origin', xy = (0, 0)) +title('Four Plot') +xlim(-5*pi, 5*pi) +ylim(-5*pi, 5*pi) +#show() diff -r e675f9208b91 -r 4054b1a6392d using python modules/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,120 @@ +Objective Questions +------------------- + +.. A mininum of 8 questions here (along with answers) + +1. What will be output of the following code snippet, + :: + + from math import sqrt + + def sqrt(i): + return i + + print sqrt(49) + + a. 7.0 + #. 7 + #. 49 + #. 49.0 + #. Error + +Answer: 49 + +2. What will be the output of the following code snippet, + :: + + import math + + def sqrt(i): + x = math.sqrt(i) + if int(x) == x: + return int(x) + else: + return x + + print math.sqrt(50), sqrt(50), math.sqrt(49), sqrt(49) + + a. 7.0710678118654755 7 7 7 + #. 7.0710678118654755 7 7.0 7 + #. 7 7 7 7 + #. 7.0710678118654755 7.0710678118654755 7.0 7 + +Answer: 7.0710678118654755, 7.0710678118654755, 7.0, 7 + +3. ``from math import *`` and ``import math`` does the same, + + a. True + #. False + +Answer: False + +4. Which among these libraries is part of python standard library, + + a. Mayavi + #. scipy + #. matplotlib + #. urllib2 + +Answer: urllib2 + +5. ``pylab.plot(x,sin(x))`` can be used in a script with ``from pylab + import *`` + + a. True + #. False + +Answer: False + +6. Which among this is correct, + + a. from scipy import plot + #. from numpy import plot + #. from matplotlib import plot + #. from pylab import plot + #. None of the above + +Answer: from pylab import plot + +7. Functions ``xlim()`` and ``ylim()`` can be imported to the current + name-space as, + + a. from pylab import xlim, ylim + #. import pylab + #. from scipy import xlim, ylim + #. import scipy + +Answer: from pylab import xlim, ylim + +8. ``scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500)`` + + a. creates an array of 500 equally spaced elements from -5*scipy.pi + to 5*scipy.pi(excluded) + #. creates an array of 500 equally spaced elements from + -5*scipy.pi(excluded) to 5*scipy.pi(included) + #. creates an array of 500 equally spaced elements from -5*scipy.pi + to 5*scipy.pi, both end points included + #. created an array of 500 equally spaced elements from -5*scipy.pi + to 5*scipy.pi, both end points excluded. + #. None of the above + +Answer: creates an array of 500 equally spaced elements from + -5*scipy.pi to 5*scipy.pi, both end points included + + +Larger Questions +---------------- + +.. A minimum of 2 questions here (along with answers) + +1. Write a python script to plot a red colour tan plot between -pi to + pi, with x limits from -pi to pi. Label the figure appropriately + and with a legend 'tan(x)' and title 'tangent plot'. Label the axes + x as 'x' and y as 'tan(x)'. Make sure the script can be executed as + a python script. + +2. Write a python script to plot a parabola of the form y^2=4ax with a + = 0.5(a is the directrix), plot the line in green color add the + legend as 'y^2=4ax' and title as 'parabola'. For x from -20 to 20 + with 100 equidistant points. Make sure the script can be executed + as a python script. [`Hint`: Use parametric equations] diff -r e675f9208b91 -r 4054b1a6392d using python modules/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,247 @@ +.. Objectives +.. ---------- + +.. At the end of this tutorial, you will be able to + +.. 1. Execute python scripts from command line. +.. #. Use import in scripts. +.. #. Import scipy and pylab modules +.. #. Use python standard modules and 3rd party modules. + + +.. Prerequisites +.. ------------- + +.. 1. should have ``pylab`` installed. +.. #. using plot command interactively. +.. #. embellishing a plot. +.. #. saving plots. + +.. Author : Anoop Jacob Thomas + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + + +==================== +Using Python modules +==================== +{{{ show the welcome slide }}} + +Welcome to the spoken tutorial on using python modules. + +{{{ switch to next slide, outline slide }}} + +In this tutorial, we will see how to run python scripts from command +line, importing modules, importing scipy and pylab modules. And also +see the Python standard library. + +{{{ switch to next slide on executing python scripts from command line }}} + +Let us create a simple python script to print hello world. Open your +text editor and type the following, + +{{{ open the text editor and type the following }}} +:: + + print "Hello world!" + print + +and save the script as hello.py, + +{{{ save the script as hello.py }}} + +Till now we saw how to run a script using the IPython interpreter +using the +:: + + %run -i hello.py + +option, but that is not the correct way of running a python +script. + +The correct method is to run it using the Python interpreter. Open the +terminal and navigate to the directory where hello.py is, + +{{{ open terminal and navigate to directory where hello.py was saved }}} + +{{{ switch to next slide }}} + +now run the Python script as, +:: + + python hello.py + +It executed the script and we got the output ``Hello World!``. + +{{{ highlight ``python filename`` syntax on slide while narrating }}} + +The syntax is python space filename. + +{{{ switch to next slide, four plot problem }}} + +Now recall the four plot problem where we plotted four plots in a single +figure. Let us run that script from command line. + +If you don't have the script, + +{{{ open the four_plot.py file in text editor }}} + +just pause here and create a python script with the following lines +and save it as four_plot.py. + +Now let us run four_plot.py as a python script. +:: + + python four_plot.py + +Oops! even though it was supposed to work, it didn't. It gave an error +``linspace()`` is not defined, which means that the function +``linspace()`` is not available in the current name-space. + +But if you try to run the same script using ``%run -i four_plot.py`` +in your IPython interpreter started with the option ``-pylab`` it will +work, because the ``-pylab`` option does some work for us by importing +the required modules to our name-space when ipython interpreter +starts. And thus we don't have to explicitly import modules. + +So now let us try to fix the problem and run the script in command +line, + +{{{ switch to next slide, fix ``linspace`` problem }}} + +add the following line as the first line in the script, +{{{ add the line as first line in four_plot.py and save }}} +:: + + from scipy import * + +Now let us run the script again, +:: + + python four_plot.py + +Now it gave another error plot not defined, let us edit the file again +and add the line below the line we just added, + +{{{ switch to next slide, fix ``plot`` problem }}} + +{{{ add the line as second line in four_plot.py and save }}} +:: + + from pylab import * + +And run the script, +:: + + python four_plot.py + +Yes! it worked. So what did we do? + +We actually imported the required modules using the keyword ``import``. +It could have also be done as, + +{{{ switch to next slide, better way of fixing }}} + +{{{ highlight the following in slide and say it loud }}} +:: + + from scipy import linspace + +instead of, +:: + + from scipy import * + +So in practice it is always good to use function names instead of +asterisk or star. As if we use asterisk to import from a particular +module then it will replace any existing functions with the same name +in our name-space. + +{{{ switch to next slide, Instead of ``*`` }}} + +So let us modify four_plot.py as, +{{{ delete the first two lines and add the following }}} +:: + + from scipy import linspace, pi, sin + from pylab import plot, legend, annotate + from pylab import xlim, ylim, title, show + +Now let us try running the code again as, +:: + + python four_plot.py + +It works! In this method we actually imported the functions to the +current name-space, and there is another method of doing it. And that +is, + +{{{ switch to next slide }}} + +Notice that we use ``scipy.pi`` instead of just ``pi`` as in the +previous method, and the functions are called as ``pylab.plot()`` and +``pylab.annotate()`` and not as ``plot()`` and ``annotate()``. + +{{{ switch to next slide, problem statement }}} + +Write a script to plot a sine wave from minus two pi to two pi. + +Pause here and try to solve the problem yourself before looking at the +solution. + +It can solved as, + +{{{ open sine.py and show it }}} + +the first line we import the required functions ``linspace()`` and +``sin()`` and constant ``pi`` from the module scipy. the second and +third line we import the functions ``plot()``, ``legend()``, +``show()``, ``title()``, ``xlabel()`` and ``ylabel()``. And the rest +the code to generate the plot. + +We can run it as, +{{{ now switch focus to terminal and run the script }}} +:: + + python sine.py + +{{{ switch to next slide, What is a module? }}} + +So till now we have been learning about importing modules, now what is +a module? + +A module is simply a file containing Python definitions and +statements. Definitions from a module can be imported into other +modules or into the main module. + +{{{ switch to next slide, Python standard library }}} + +Python has a very rich standard library of modules + +Python's standard library is very extensive, offering a wide range of +facilities. Some of the standard modules are, + +for Math: math, random +for Internet access: urllib2, smtplib +for System, Command line arguments: sys +for Operating system interface: os +for regular expressions: re +for compression: gzip, zipfile, tarfile +And there are lot more. + +Find more information at Python Library reference, +``http://docs.python.org/library/`` + +The modules pylab, scipy, Mayavi are not part of the standard python +library. + +{{{ switch to next slide, summary }}} + +This brings us to the end of this tutorial, in this tutorial we +learned running scripts from command line, learned about modules, saw +the python standard library. + +{{{ switch to next slide, thank you slide }}} + +Thank you! diff -r e675f9208b91 -r 4054b1a6392d using python modules/sine.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/sine.py Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,11 @@ +from scipy import linspace, pi, sin +from pylab import plot, legend, show, title +from pylab import xlabel, ylabel + +x = linspace(-2*pi,2*pi,100) +plot(x,sin(x)) +legend(['sin(x)']) +title('Sine plot') +xlabel('x') +ylabel('sin(x)') +show() diff -r e675f9208b91 -r 4054b1a6392d using python modules/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,125 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: Using python modules +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Running python scripts from command line + - Importing python modules + - Importing scipy \& pylab modules + - About python standard library. +* Running Python script from command line + - Create a script, open text editor and type the following + : print "hello world!" + : print + - Save the script as ~hello.py~ +* Running Python script from command line (cont'd) + - Run the script + : $ python hello.py + /Syntax :/ *python filename* +* Four plot problem + #+begin_latex + \begin{center} + \includegraphics[scale=0.4]{four_plot} + \end{center} + #+end_latex +* Fix ~linspace()~ problem + : from scipy import * +* Fix ~plot()~ problem + : from pylab import * +* Better way of fixing + : from scipy import linspace + instead of + : from scipy import * + ~*~ means import all functions from name-space ~scipy~. +* Instead of ~*~ + : from scipy import linspace, pi, sin + : from pylab import plot, legend, annotate + : from pylab import xlim, ylim, title, show + Is better than, ~from scipy import *~ \& ~from pylab import *~. +* Another Fix + #+begin_src python + import scipy + import pylab + x = scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500) + pylab.plot(x, x, 'b') + pylab.plot(x, -x, 'b') + pylab.plot(x, scipy.sin(x), 'g', linewidth=2) + pylab.plot(x, x*scipy.sin(x), 'r', linewidth=3) + pylab.legend(['x', '-x', 'sin(x)', 'xsin(x)']) + pylab.annotate('origin', xy = (0, 0)) + pylab.xlim(-5*scipy.pi, 5*scipy.pi) + pylab.ylim(-5*scipy.pi, 5*scipy.pi) + #+end_src +* Exercise 1 + Write a python script to plot a sine wave from + #+begin_latex + $-2\Pi$ + #+end_latex + to + #+begin_latex + $2\Pi$ + #+end_latex + . +* What is a module? + Module is simply a file containing Python definitions and + statements. Definitions from a module can be imported into other + modules or into the main module. +* Python standard library + Python has a very rich standard library of modules. + - Few libraries + - Math: ~math~, ~random~ + - Internet access: ~urllib2~, ~smtplib~ + - System, Command line arguments: ~sys~ + - Operating system interface: ~os~ + - regular expressions: ~re~ + - compression: ~gzip~, ~zipfile~, ~tarfile~ + - More information + - [[http://docs.python.org/library]] +* Summary + - Running scripts from command line + - Learned about modules + - importing modules + - Python standard library +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d using python modules/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,227 @@ +% Created 2010-10-12 Tue 17:12 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{t1enc} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Using python modules} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Running python scripts from command line +\item Importing python modules +\item Importing scipy \& pylab modules +\item About python standard library. +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Running Python script from command line} +\label{sec-2} + +\begin{itemize} +\item Create a script, open text editor and type the following +\begin{verbatim} + print "hello world!" + print +\end{verbatim} + +\item Save the script as \texttt{hello.py} +\end{itemize} +\end{frame} +\begin{frame}[fragile] +\frametitle{Running Python script from command line (cont'd)} +\label{sec-3} + +\begin{itemize} +\item Run the script +\begin{verbatim} + $ python hello.py +\end{verbatim} + +\end{itemize} + + \emph{Syntax :} \textbf{python filename} +\end{frame} +\begin{frame} +\frametitle{Four plot problem} +\label{sec-4} + + \begin{center} + \includegraphics[scale=0.4]{four_plot} + \end{center} +\end{frame} +\begin{frame}[fragile] +\frametitle{Fix \texttt{linspace()} problem} +\label{sec-5} + +\begin{verbatim} + from scipy import * +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Fix \texttt{plot()} problem} +\label{sec-6} + +\begin{verbatim} + from pylab import * +\end{verbatim} +\end{frame} +\begin{frame}[fragile] +\frametitle{Better way of fixing} +\label{sec-7} + +\begin{verbatim} + from scipy import linspace +\end{verbatim} + + instead of +\begin{verbatim} + from scipy import * +\end{verbatim} + + \texttt{*} means import all functions from name-space \texttt{scipy}. +\end{frame} +\begin{frame}[fragile] +\frametitle{Instead of \texttt{*}} +\label{sec-8} + +\begin{verbatim} + from scipy import linspace, pi, sin + from pylab import plot, legend, annotate + from pylab import xlim, ylim, title, show +\end{verbatim} + + Is better than, \texttt{from scipy import *} \& \texttt{from pylab import *}. +\end{frame} +\begin{frame}[fragile] +\frametitle{Another Fix} +\label{sec-9} + +\begin{verbatim} +import scipy +import pylab +x = scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500) +pylab.plot(x, x, 'b') +pylab.plot(x, -x, 'b') +pylab.plot(x, scipy.sin(x), 'g', linewidth=2) +pylab.plot(x, x*scipy.sin(x), 'r', linewidth=3) +pylab.legend(['x', '-x', 'sin(x)', 'xsin(x)']) +pylab.annotate('origin', xy = (0, 0)) +pylab.xlim(-5*scipy.pi, 5*scipy.pi) +pylab.ylim(-5*scipy.pi, 5*scipy.pi) +\end{verbatim} +\end{frame} +\begin{frame} +\frametitle{Exercise 1} +\label{sec-10} + + Write a python script to plot a sine wave from + $-2\Pi$ + to + $2\Pi$ + . +\end{frame} +\begin{frame} +\frametitle{What is a module?} +\label{sec-11} + + Module is simply a file containing Python definitions and + statements. Definitions from a module can be imported into other + modules or into the main module. +\end{frame} +\begin{frame} +\frametitle{Python standard library} +\label{sec-12} + + Python has a very rich standard library of modules. +\begin{itemize} +\item Few libraries + +\begin{itemize} +\item Math: \texttt{math}, \texttt{random} +\item Internet access: \texttt{urllib2}, \texttt{smtplib} +\item System, Command line arguments: \texttt{sys} +\item Operating system interface: \texttt{os} +\item regular expressions: \texttt{re} +\item compression: \texttt{gzip}, \texttt{zipfile}, \texttt{tarfile} +\end{itemize} + +\item More information + +\begin{itemize} +\item \href{http://docs.python.org/library}{http://docs.python.org/library} +\end{itemize} + +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-13} + +\begin{itemize} +\item Running scripts from command line +\item Learned about modules + +\begin{itemize} +\item importing modules +\end{itemize} + +\item Python standard library +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-14} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document} diff -r e675f9208b91 -r 4054b1a6392d using-sage/questions.rst --- a/using-sage/questions.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/using-sage/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,17 +1,81 @@ Objective --------- -.. A mininum of 8 questions here. +1. How do you find the limit of the function ``x/sin(x)`` as ``x`` tends to + ``0`` from the negative side. + + Answer: lim(x/sin(x), x=0, dir="below") + +#. Find the third differential of the function ``exp(sin(x)*cos(x^2))`` + + Answer: diff(exp(sin(x)*cos(x^2), x, 3) + +#. Solve the system of linear equations:: + + x-2y+3z = 7 + 2x+3y-z = 5 + x+2y+4z = 9 + + Answer:: + + A = Matrix([[1, -2, 3], + [2, 3, -1], + [1, 2, 4]]) + + b = vector([7, 5, 9]) + + solve_right(A, b) + +#. How do you get the factorized form of ``x^4 - 4x^2 + x^3 + 2x + 7`` + + Answer:: -1. Question 1 -2. Question 2 -3. Question 3 + factor( x^4 + x^3 - 4*x^2 + 2*x + 7 ) + +#. list all the primes between 2009 and 2900 + + Answer: prime_range(2009, 2901) + +#. Which function is used to check primality + + a. isPrime + #. isprime + #. is_prime + #. prime + + Answer: is_prime + +#. How do you list all the combinations of ``[1, 2, 3, 4]`` + + + Answer:: + + c1 = Combinations([1, 2, 3, 4]) + c1.list() + +#. How do you list all the permutations of ``[1, 3, 2, 3]`` + + Answer:: + + p1 = Permutations([1, 3, 2, 3]) + p2.list() Programming ----------- -.. A minimum of 2 questions here. +1. What is the out put of the following code:: + + c1 = Combinations([1, 2, 3, 4]) + c2 = Combinations([1, 2, 4, 3]) + + l1 = c1.list() + l2 = c2.list() -1. Programming Assignment 1 -2. Programming Assignment 2 + for i in l2: + l1.remove(i) + + print l2 + + Answer: [] + diff -r e675f9208b91 -r 4054b1a6392d using-sage/script.rst --- a/using-sage/script.rst Wed Oct 13 17:32:23 2010 +0530 +++ b/using-sage/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -1,10 +1,29 @@ -======== - Script -======== +.. Objectives +.. ---------- + +.. By the end of this tutorial you will -- + +.. 1. Get an idea of the range of things for which Sage can be used. +.. #. Know some of the functions for Calculus +.. #. Get some insight into Graphs in Sage. + + +.. Prerequisites +.. ------------- + +.. Getting Started -- Sage + +.. Author : Puneeth + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ {{{ show the welcome slide }}} -Welcome to this tutorial on using Sage. +Hello Friends. Welcome to this tutorial on using Sage. {{{ show the slide with outline }}} @@ -194,4 +213,8 @@ We have looked at some of the functions available for Linear Algebra, Calculus, Graph Theory and Number theory. -Thank You! +This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India + +Hope you have enjoyed and found it useful. +Thank you! + diff -r e675f9208b91 -r 4054b1a6392d using-sage/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using-sage/slides.org Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,60 @@ +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] +#+BEAMER_FRAME_LEVEL: 1 + +#+BEAMER_HEADER_EXTRA: \usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +#+COLUMNS: %45ITEM %10BEAMER_env(Env) %10BEAMER_envargs(Env Args) %4BEAMER_col(Col) %8BEAMER_extra(Extra) +#+PROPERTY: BEAMER_col_ALL 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 :ETC + +#+LaTeX_CLASS: beamer +#+LaTeX_CLASS_OPTIONS: [presentation] + +#+LaTeX_HEADER: \usepackage[english]{babel} \usepackage{ae,aecompl} +#+LaTeX_HEADER: \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} + +#+LaTeX_HEADER: \usepackage{listings} + +#+LaTeX_HEADER:\lstset{language=Python, basicstyle=\ttfamily\bfseries, +#+LaTeX_HEADER: commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +#+LaTeX_HEADER: showstringspaces=false, keywordstyle=\color{blue}\bfseries} + +#+TITLE: using Sage +#+AUTHOR: FOSSEE +#+EMAIL: +#+DATE: + +#+DESCRIPTION: +#+KEYWORDS: +#+LANGUAGE: en +#+OPTIONS: H:3 num:nil toc:nil \n:nil @:t ::t |:t ^:t -:t f:t *:t <:t +#+OPTIONS: TeX:t LaTeX:nil skip:nil d:nil todo:nil pri:nil tags:not-in-toc + +* Outline + - Calculus + - Linear Algebra + - Graph Theory + - Number Theory +* Summary + - Differentiating and Integrating + - Taylor Expansions + - Solving Equations + - Initializing Graphs & Graph families + - Prime numbers + - Factors + - Combinations & Permutations +* Thank you! +#+begin_latex + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +#+end_latex + + diff -r e675f9208b91 -r 4054b1a6392d using-sage/slides.tex --- a/using-sage/slides.tex Wed Oct 13 17:32:23 2010 +0530 +++ b/using-sage/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -1,95 +1,74 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -%\documentclass[draft]{beamer} -%\documentclass[compress,handout]{beamer} -%\usepackage{pgfpages} -%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] - -% Modified from: generic-ornate-15min-45min.de.tex -\mode -{ - \usetheme{Warsaw} - \useoutertheme{infolines} - \setbeamercovered{transparent} -} - -\usepackage[english]{babel} +% Created 2010-10-11 Mon 22:48 +\documentclass[presentation]{beamer} \usepackage[latin1]{inputenc} -%\usepackage{times} \usepackage[T1]{fontenc} - -\usepackage{ae,aecompl} -\usepackage{mathpazo,courier,euler} -\usepackage[scaled=.95]{helvet} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} -\definecolor{darkgreen}{rgb}{0,0.5,0} - -\usepackage{listings} -\lstset{language=Python, - basicstyle=\ttfamily\bfseries, - commentstyle=\color{red}\itshape, - stringstyle=\color{darkgreen}, - showstringspaces=false, - keywordstyle=\color{blue}\bfseries} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Macros -\setbeamercolor{emphbar}{bg=blue!20, fg=black} -\newcommand{\emphbar}[1] -{\begin{beamercolorbox}[rounded=true]{emphbar} - {#1} - \end{beamercolorbox} -} -\newcounter{time} -\setcounter{time}{0} -\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} - -\newcommand{\typ}[1]{\lstinline{#1}} - -\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } - -% Title page -\title{Your Title Here} - -\author[FOSSEE] {FOSSEE} - -\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\title{using Sage} +\author{FOSSEE} \date{} -% DOCUMENT STARTS +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} \begin{document} +\maketitle + + + + + + + + + \begin{frame} - \maketitle -\end{frame} +\frametitle{Outline} +\label{sec-1} -\begin{frame}[fragile] - \frametitle{Outline} - \begin{itemize} - \item - \end{itemize} +\begin{itemize} +\item Calculus +\item Linear Algebra +\item Graph Theory +\item Number Theory +\end{itemize} \end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-2} -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% All other slides here. %% -%% The same slides will be used in a classroom setting. %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\begin{itemize} +\item Differentiating and Integrating +\item Taylor Expansions +\item Solving Equations +\item Initializing Graphs \& Graph families +\item Prime numbers +\item Factors +\item Combinations \& Permutations +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-3} -\begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Thank you!} \begin{block}{} \begin{center} This spoken tutorial has been produced by the diff -r e675f9208b91 -r 4054b1a6392d using_sage_to_teach.rst --- a/using_sage_to_teach.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,40 +0,0 @@ -Hello friends and welcome to the tutorial on "How to use SAGE for teaching" - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall learn - - * How to use SAGE for 2D and 3D plotting - * How to use interactive features of SAGE for better demonstration - * How to use SAGE worksheets for collaborative learning - * How to use typesetting in sage for neater outputs - -{{{ 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 use loadtxt to read files - * 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. -Thankyou - -.. Author : Nishanth - Internal Reviewer 1 : - Internal Reviewer 2 : - External Reviewer : diff -r e675f9208b91 -r 4054b1a6392d using_sage_to_teach/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_sage_to_teach/questions.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,36 @@ +Objective Questions +------------------- + + 1. which default argument, when used with ``@interact`` gives a slider + starting at 0 and ending in 10 + + a. (0..11) + #. range(0, 11) + #. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + #. (0..10) + + Answer: (0..10) + + 2. What is the input widget resulted by using ``n = [2, 4, 5, 9]`` in the + default arguments along with ``@interact`` + + a. input field + #. set of buttons + #. slider + #. None + + Answer: set of buttons + + 3. what is the type of ``n`` in the following function:: + + @interact + def f(n=2.5): + # do something with n + + a. int + #. float + #. string + #. complex + + Answer: float + diff -r e675f9208b91 -r 4054b1a6392d using_sage_to_teach/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_sage_to_teach/quickref.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d using_sage_to_teach/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_sage_to_teach/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,181 @@ +.. 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 "Using SAGE to teach" + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall learn + + * How to use the "@interact" feature of SAGE for better demonstration + * How to use SAGE for collaborative learning + +Let us look at a typical example of demonstrating a damped oscillation. +:: + + t = var('t') + p1 = plot( e^(-t) * sin(2*t), (t, 0, 15)) + show(p1) + +Now let us reduce the damping factor +:: + + t = var('t') + p1 = plot( e^(-t/2) * sin(2*t), (t, 0, 15)) + show(p1) + +Now if we want to reduce the damping factor even more, we would be using +e^(-t/3). We can observe that every time we have to change, all we do is change +something very small and re evaluate the cell. + +This process can be automated using the ``@interact`` feature of SAGE. + +:: + + @interact + def plot_damped(n=1): + t = var('t') + p1 = plot( e^(-t/n) * sin(2*t), (t, 0, 20)) + show(p1) + +We can see that the function is evaluated and the plot is shown. We can also +see that there is a field to enter the value of ``n`` and it is currently set +to ``1``. Let us change it to 2 and hit enter. + +We see that the new plot with reduced damping factor is shown. Similarly we can +change ``n`` to any desired value and hit enter and the function will be +evaluated. + +This is a very handy tool while demonstrating or teaching. + +{{{ Pause here and try out the following exercises }}} + +%% 1 %% Plot the sine curve and vary its frequency using the ``@interact`` + +{{{ continue from paused state }}} + +:: + + @interact + def sine_plot(n=1): + x = var('x') + p2 = plot(sin(n*x), (x, 0, 2*pi)) + show(p2) + +Often we would want to vary a parameter over range instead of taking it as an +input from the user. For instance we do not want the user to give ``n`` as 0 +for the damping oscillation we discussed. In such cases we use a range of +values as the default argument. +:: + + @interact + def plot_damped(n=(1..10)): + t = var('t') + p1 = plot( e^(-t/n) * sin(2*t), (t, 0, 20)) + show(p1) + +We get similar plot but the only difference is the input widget. Here it is a +slider unlike an input field. We can see that as the slider is moved, the +function is evaluated and plotted accordingly. + +{{{ Pause here and try out the following exercises }}} + +%% 2 %% Take a string as input from user and circular shift it to the left and + vary the shift length using a slider + +{{{ continue from paused state }}} + +:: + + @interact + def str_shift(s="MADAM", shift=(0..8)): + shift_len = shift % len(s) + chars = list(s) + shifted_chars = chars[shift_len:] + chars[:shift_len] + print "Actual String:", s + print "Shifted String:", "".join(shifted_chars) + +Sometimes we want the user to have only a given set of options. We use a list +of items as the default argument in such situations. +:: + + @interact + def str_shift(s="STRING", shift=(0..8), direction=["Left", "Right"]): + shift_len = shift % len(s) + chars = list(s) + if direction == "Right": + shifted_chars = chars[-shift_len:] + chars[:-shift_len] + else: + shifted_chars = chars[shift_len:] + chars[:shift_len] + print "Actual String:", s + print "Shifted String:", "".join(shifted_chars) + +We can see that buttons are displayed which enables us to select from a given +set of options. + +We have learnt how to use the ``@interact`` feature of SAGE for better +demonstration. We shall look at how to use SAGE worksheets for collaborative +learning. + +The first feature we shall see is the ``publish`` feature. Open a worksheet and +in the top right, we can see a button called ``publish``. Click on that and we +get a confirmation page with an option for re publishing. + +For now lets forget that opion and simply publish by cliking ``yes``. The +worksheet is now published. + +Now lets signout and go to the sage notebook home. We see link to browse +published worksheets. Lets click on it and we can see the worksheet. This does +not require login and anyone can view the worksheet. + +Alternatively, if one wants to edit the sheet, there is a link on top left +corner that enables the user to download a copy of the sheet onto their home. +This way they can edit a copy of the worksheet. + +We have learnt how to publish the worksheets to enable users to edit a copy. +Next, we shall look at how to enable users to edit the actual worksheet itself. + +Let us open the worksheet and we see a link called ``share`` on the top right +corner of the worksheet. Click the link and we get a box where we can type the +usernames of users whom we want to share the worksheet with. We can even +specify multiple users by seperating their names using commas. Once we have +shared the worksheet, the worksheet appears on the home of shared users. + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have learnt + + * How to user interactive feaures of SAGE + * How to publish our work + * How to edit a copy of one of the published worksheets + * How to share the worksheets with fellow users + +{{{ 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 e675f9208b91 -r 4054b1a6392d using_sage_to_teach/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using_sage_to_teach/slides.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d writing_python_scripts.rst --- a/writing_python_scripts.rst Wed Oct 13 17:32:23 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,136 +0,0 @@ -Hello friends and welcome to the tutorial on "Writing Python scripts" - -{{{ Show the slide containing title }}} - -{{{ Show the slide containing the outline slide }}} - -In this tutorial, we shall learn - - * How write Python scripts - -Often we will have to reuse the code that we haave written. We do that by -writing functions. Functions are bundled into packages and are imported as and -required in the script. - -Let us first write a function that computes the gcd of two numbers and save it -in a script. - -{{{ Open an editor and start typing out the following code }}} -:: - - def gcd(a, b): - - while b: - a, b = b, a%b - - return a - -We shall write an test function in the script that tests the gcd function every -time the script is run. - -{{{ Add to the script }}} - -:: - - if gcd(40, 12) == 4: - print "Everything OK" - else: - print "The GCD function is wrong" - -Let us save the file as script.py in /home/fossee/gcd_script.py - -We shall run the script by doing -:: - - $ python /home/fossee/gcd_script.py - -We can see that the script is executed and everything is fine. - -What if we want to use the gcd function in some of our later scripts. This -is also possible since every python file can be used as a module. - -But first, we shall understand what happens when you import a module. - -Open IPython and type -:: - - import sys - sys.path - -This is a list of locations where python searches for a module when it -encounters an import statement. - -hence when we just did =import sys=, python searches for a file named sys.py or -a folder named sys in all these locations one by one, until it finds one. - -We can place our script in any one of these locations and can import it. - -The first item in the list is an empty string which means the current working -directory is also searched. - -Alternatively, we can also import the module if we are working in same -directory where the script exists. - -Since we are in /home/fossee, we can simply do -:: - - import gcd_script - -We can see that the gcd_script is imported. But the test code that we added at -the end of the file is also executed. - -But we want the test code to be executed only when the file is run as a python -script and not when it is imported. - -This is possible by using =__name__= variable. - -First we shall look at how to use the idiom and then understand how it works. - -Go to the file and add -:: - - if __name__ == "__main__": - -before the test code and indent the test code. - -Let us first run the code. -:: - - $ python gcd_script.py - -We can see that the test runs successfully. - -Now we shall import the file -:: - - import gcd_script - -We see that now the test code is not executed. - -The __name__ variable is local to every module and it is equal to __main__ only -when the file is run as a script. - -hence all the code that goes after __name__ == "__main__" is executed only when -the file is run as a python script. - -{{{ Show summary slide }}} - -This brings us to the end of the tutorial. -we have learnt - - * What happens when we import a module - * How to use a script as a module - * How to write test functions using the __name__ idiom - -{{{ 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 : diff -r e675f9208b91 -r 4054b1a6392d writing_python_scripts/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/writing_python_scripts/questions.rst Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d writing_python_scripts/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/writing_python_scripts/quickref.tex Wed Oct 13 17:32:59 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 e675f9208b91 -r 4054b1a6392d writing_python_scripts/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/writing_python_scripts/script.rst Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,146 @@ +.. Objectives +.. ---------- + +.. Prerequisites +.. ------------- + +.. Author : Nishanth Amuluru + Internal Reviewer : + External Reviewer : + Checklist OK? : [2010-10-05] + +Script +------ + +Hello friends and welcome to the tutorial on "Writing Python scripts" + +{{{ Show the slide containing title }}} + +{{{ Show the slide containing the outline slide }}} + +In this tutorial, we shall learn + + * How write Python scripts + +Often we will have to reuse the code that we haave written. We do that by +writing functions. Functions are bundled into packages and are imported as and +required in the script. + +Let us first write a function that computes the gcd of two numbers and save it +in a script. + +{{{ Open an editor and start typing out the following code }}} +:: + + def gcd(a, b): + + while b: + a, b = b, a%b + + return a + +We shall write an test function in the script that tests the gcd function every +time the script is run. + +{{{ Add to the script }}} + +:: + + if gcd(40, 12) == 4: + print "Everything OK" + else: + print "The GCD function is wrong" + +Let us save the file as script.py in /home/fossee/gcd_script.py + +We shall run the script by doing +:: + + $ python /home/fossee/gcd_script.py + +We can see that the script is executed and everything is fine. + +What if we want to use the gcd function in some of our later scripts. This +is also possible since every python file can be used as a module. + +But first, we shall understand what happens when you import a module. + +Open IPython and type +:: + + import sys + sys.path + +This is a list of locations where python searches for a module when it +encounters an import statement. + +hence when we just did =import sys=, python searches for a file named sys.py or +a folder named sys in all these locations one by one, until it finds one. + +We can place our script in any one of these locations and can import it. + +The first item in the list is an empty string which means the current working +directory is also searched. + +Alternatively, we can also import the module if we are working in same +directory where the script exists. + +Since we are in /home/fossee, we can simply do +:: + + import gcd_script + +We can see that the gcd_script is imported. But the test code that we added at +the end of the file is also executed. + +But we want the test code to be executed only when the file is run as a python +script and not when it is imported. + +This is possible by using =__name__= variable. + +First we shall look at how to use the idiom and then understand how it works. + +Go to the file and add +:: + + if __name__ == "__main__": + +before the test code and indent the test code. + +Let us first run the code. +:: + + $ python gcd_script.py + +We can see that the test runs successfully. + +Now we shall import the file +:: + + import gcd_script + +We see that now the test code is not executed. + +The __name__ variable is local to every module and it is equal to __main__ only +when the file is run as a script. + +hence all the code that goes after __name__ == "__main__" is executed only when +the file is run as a python script. + +{{{ Show summary slide }}} + +This brings us to the end of the tutorial. +we have learnt + + * What happens when we import a module + * How to use a script as a module + * How to write test functions using the __name__ idiom + +{{{ 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 e675f9208b91 -r 4054b1a6392d writing_python_scripts/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/writing_python_scripts/slides.tex Wed Oct 13 17:32:59 2010 +0530 @@ -0,0 +1,104 @@ +% Created 2010-10-10 Sun 23:53 +\documentclass[presentation]{beamer} +\usepackage[latin1]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Sets} +\author{FOSSEE} +\date{} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + + + + + + + + + +\begin{frame} +\frametitle{Outline} +\label{sec-1} + +\begin{itemize} +\item Defining Sets +\item Operations on sets +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Question 1} +\label{sec-2} + + Given a list of marks, \texttt{marks = [20, 23, 22, 23, 20, 21, 23]} list + all the duplicates +\end{frame} +\begin{frame}[fragile] +\frametitle{Solution 1} +\label{sec-3} + +\lstset{language=Python} +\begin{lstlisting} +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) +\end{lstlisting} +\end{frame} +\begin{frame} +\frametitle{Summary} +\label{sec-4} + + You should now be able to -- +\begin{itemize} +\item make sets from lists +\item input sets directly +\item perform operations like union, intersection, symmetric difference +\item check if a subset of another +\item check containership, length and other properties similar to lists +\end{itemize} +\end{frame} +\begin{frame} +\frametitle{Thank you!} +\label{sec-5} + + \begin{block}{} + \begin{center} + This spoken tutorial has been produced by the + \textcolor{blue}{FOSSEE} team, which is funded by the + \end{center} + \begin{center} + \textcolor{blue}{National Mission on Education through \\ + Information \& Communication Technology \\ + MHRD, Govt. of India}. + \end{center} + \end{block} +\end{frame} + +\end{document}