# HG changeset patch # User Puneeth Chaganti # Date 1286948737 -19800 # Node ID c6d31837cb06d9889005346a24dd4b9db05426b2 # Parent 4bebfa8c9a0a2eb68cfbd2d5e96046cd89b8d51e# Parent 9d8fd5ea64b248143ad2b1d40fa03a88f3d49723 Merged heads. diff -r 4bebfa8c9a0a -r c6d31837cb06 additional_ipython/quickref.tex --- a/additional_ipython/quickref.tex Wed Oct 13 11:15:18 2010 +0530 +++ b/additional_ipython/quickref.tex Wed Oct 13 11:15:37 2010 +0530 @@ -1,11 +1,15 @@ -Creating a tuple:\\ -{\ex \lstinline| t = (1, "hello", 2.5)|} +accessing history:\\ +{\ex \lstinline| \%hist|} -Accessing elements of tuples:\\ -{\ex \lstinline| t[index] Ex: t[2]|} +accessing particular line of history:\\ +{\ex \lstinline| \%hist line_number|} -Accessing slices of tuples:\\ -{\ex \lstinline| t[start:stop:step]|} +accessing particular range of history:\\ +{\ex \lstinline| \%hist start_line stop_line|} -Swapping values:\\ -{\ex \lstinline| a, b = b, a|} +saving history to a file:\\ +{\ex \lstinline| \%save file_path line_numbers|} + +running a script:\\ +{\ex \lstinline| \%run -i file_path|} + diff -r 4bebfa8c9a0a -r c6d31837cb06 advanced-features-functions/questions.rst --- a/advanced-features-functions/questions.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/advanced-features-functions/questions.rst Wed Oct 13 11:15:37 2010 +0530 @@ -17,6 +17,9 @@ #. only keyword arguments can be in any order, but should be called at the end. + Answer: only keyword arguments can be in any order, but should be called + at the end. + #. Given the following function, identify the keywords with default values. :: @@ -101,8 +104,6 @@ Larger Questions ---------------- -.. A minimum of 2 questions here (along with answers) - 1. 2. diff -r 4bebfa8c9a0a -r c6d31837cb06 dictionaries/script.rst --- a/dictionaries/script.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/dictionaries/script.rst Wed Oct 13 11:15:37 2010 +0530 @@ -35,6 +35,8 @@ {{{ 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. :: @@ -74,6 +76,8 @@ 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, :: @@ -153,14 +157,16 @@ exercise }}} Now let us try to print the data in the dictionary. We can use ``for`` -loop to iterate. +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, recap }}} +{{{ 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 diff -r 4bebfa8c9a0a -r c6d31837cb06 dictionaries/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dictionaries/slides.org Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 dictionaries/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/dictionaries/slides.tex Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 getting-started-files/questions.rst --- a/getting-started-files/questions.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/getting-started-files/questions.rst Wed Oct 13 11:15:37 2010 +0530 @@ -37,7 +37,7 @@ What is the value of content, at the end of this code block:: f = open('hello.txt') - content = f.read() + pre_content = f.read() content = f.read() f.close() @@ -126,7 +126,7 @@ .. A minimum of 2 questions here. -1. f.read(size) +1. What does ``f.read(size)`` do? #. Print every alternate line of a file, starting at the first line. diff -r 4bebfa8c9a0a -r c6d31837cb06 getting-started-with-arrays/script.rst --- a/getting-started-with-arrays/script.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/getting-started-with-arrays/script.rst Wed Oct 13 11:15:37 2010 +0530 @@ -71,6 +71,8 @@ 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, :: @@ -79,6 +81,8 @@ 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 @@ -110,7 +114,7 @@ {{{ switch to the next slide, unsolved exercise 2 }}} -Find out the shape of the other two arrays that we have created. +Find out the shape of the other arrays that we have created. {{{ Array can have only a single type of data }}} @@ -129,6 +133,8 @@ Did you notice it, +{{{ switch to next slide, implicit type casting }}} + {{{ highlight all the array elements one by one using mouse movements }}} @@ -226,7 +232,7 @@ Returns an array with element by element multiplication, notice that it does not perform matrix multiplication. -{{{ switch to next slide, recap slide }}} +{{{ 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 diff -r 4bebfa8c9a0a -r c6d31837cb06 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 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 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 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 getting-started-with-for/script.rst --- a/getting-started-with-for/script.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/getting-started-with-for/script.rst Wed Oct 13 11:15:37 2010 +0530 @@ -43,6 +43,11 @@ for indentation. Do that while typing so that they can actually see what is being typed. +As you can see in the slide, ``Block B`` is an inner block and it is +indented using 4 spaces, and after ``Block B`` the next statement in +``Block A`` starts from the same indentation level of other ``Block +A`` statements. + Now let us move straight into ``for`` loop. {{{ switch to next slide, problem statement of exercise 1 }}} @@ -85,6 +90,8 @@ square_roots. It is only complicating stuff. Simply iterate and print. +{{{ switch to next slide, save and run script }}} + {{{ save the script }}} Now save the script, and run it from your IPython interpreter. I @@ -151,6 +158,8 @@ the list. And this time let us do it right in the IPython interpreter. +{{{ switch to next slide, Indentation in ``ipython`` }}} + {{{ switch focus to the IPython interpreter }}} So let us start with making a list. Type the following @@ -166,11 +175,14 @@ four dots tell you that you are inside a block. Now type the rest of the ``for`` loop, +{{{ switch to next slide, Indentation in ``ipython`` (cont'd) }}} + .. #[Nishanth]: Tell that IPython does auto indentation. :: - print "Square root of", each, "is", sqrt(each) + print "Square root of", each, + print "is", sqrt(each) Now we have finished the statements in the block, and still the interpreter is showing four dots, which means you are still inside the @@ -178,6 +190,8 @@ without entering anything else. It printed the square root of each number in the list, and that is executed in a ``for`` loop. +{{{ switch to next slide, Indentation in ``python`` interpreter }}} + Now, let us find the cube of all the numbers from one to ten. But this time let us try it in the vanilla version of Python interpreter. @@ -187,6 +201,9 @@ {{{ open the python interpreter in the terminal using the command python to start the vanilla Python interpreter }}} +{{{ switch to next slide, Indentation in ``python`` interpreter +(cont'd) }}} + Start with, :: @@ -214,6 +231,8 @@ Then say this list can also be generated using the range function and hence introduce range. +{{{ switch to the next slide, ``range()`` function }}} + Okay! so the main thing here we learned is how to use Python interpreter and IPython interpreter to specify blocks. But while we were generating the multiplication table we used something new, @@ -225,12 +244,14 @@ .. #[Nishanth]: Show some examples of range without the step argument May be give an exercise with negative numbers as arguments -Now, let us print all the odd numbers from 1 to 50. Let us do it in -our IPython interpreter for ease of use. - {{{ switch to next slide, problem statement of the next problem in solved exercises }}} +Now, let us print all the odd numbers from 1 to 50. Pause here and try +to solve the problem yourself. + +Let us do it in our IPython interpreter for ease of use. + {{{ switch focus to ipython interpreter }}} The problem can be solved by just using the ``range()`` function. @@ -248,7 +269,7 @@ number. The third parameter is for stepping through the sequence. Here we gave two which means we are skipping every alternate element. -{{{ switch to next slide, recap slide }}} +{{{ switch to next slide, summary slide }}} Thus we come to the end of this tutorial. We learned about blocks in Python, indentation, blocks in IPython, for loop, iterating over a diff -r 4bebfa8c9a0a -r c6d31837cb06 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 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 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 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 loading-data-from-files/questions.rst --- a/loading-data-from-files/questions.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/loading-data-from-files/questions.rst Wed Oct 13 11:15:37 2010 +0530 @@ -56,8 +56,12 @@ 1. What will happen if one of the cells is empty? -#. Read a column with text? - #. 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 4bebfa8c9a0a -r c6d31837cb06 loops/questions.rst --- a/loops/questions.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/loops/questions.rst Wed Oct 13 11:15:37 2010 +0530 @@ -71,12 +71,6 @@ Answer:: - 1 - 2 - 3 - 2 - 4 - 6 3 6 9 @@ -94,5 +88,6 @@ Larger Questions ---------------- -.. A minimum of 2 questions here. +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 4bebfa8c9a0a -r c6d31837cb06 manipulating-strings/questions.rst --- a/manipulating-strings/questions.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/manipulating-strings/questions.rst Wed Oct 13 11:15:37 2010 +0530 @@ -47,11 +47,11 @@ #. Given a line from a CSV file (comma separated values), convert it to a space separated line. - Answer: line.replace(',' ' ') + Answer: line.replace(',', ' ') -#. Given the string "F.R.I.E.N.D.S" in s, obtain the friends. +#. Given the string "F.R.I.E.N.D.S" in s, obtain the "friends". - Answer: ``s[::2].lower() + Answer: ``s[::2].lower()`` Larger Questions ---------------- diff -r 4bebfa8c9a0a -r c6d31837cb06 matrices/questions.rst --- a/matrices/questions.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/matrices/questions.rst Wed Oct 13 11:15:37 2010 +0530 @@ -3,6 +3,82 @@ .. 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 ---------------- @@ -30,3 +106,11 @@ 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 4bebfa8c9a0a -r c6d31837cb06 matrices/script.rst --- a/matrices/script.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/matrices/script.rst Wed Oct 13 11:15:37 2010 +0530 @@ -22,8 +22,10 @@ {{{ switch to next slide, outline slide }}} -In this tutorial we will learn about matrices, creating matrices and -matrix operations. +In this tutorial we will learn about matrices, creating matrices using +direct data, by converting a list, matrix operations. Finding inverse +of a matrix, determinant of a matrix, eigen values and eigen vectors +of a matrix, norm and singular value decomposition of matrices. {{{ creating a matrix }}} @@ -70,6 +72,8 @@ it does matrix subtraction, that is element by element subtraction. Now let us try, + +{{{ Switch to next slide, Matrix multiplication }}} :: m3 * m2 @@ -86,6 +90,8 @@ multiply(m3,m2) +{{{ switch to next slide, Matrix multiplication (cont'd) }}} + Now let us see an example for matrix multiplication. For doing matrix multiplication we need to have two matrices of the order n by m and m by r and the resulting matrix will be of the order n by r. Thus let us @@ -106,11 +112,15 @@ {{{ switch to next slide, recall from arrays }}} -As we already saw in arrays, the functions ``identity()``, -``zeros()``, ``zeros_like()``, ``ones()``, ``ones_like()`` may also be -used with matrices. +As we already saw in arrays, the functions ``identity()`` which +creates an identity matrix of the order n by n, ``zeros()`` which +creates a matrix of the order m by n with all zeros, ``zeros_like()`` +which creates a matrix with zeros with the shape of the matrix passed, +``ones()`` which creates a matrix of order m by n with all ones, +``ones_like()`` which creates a matrix with ones with the shape of the +matrix passed. These functions can also be used with matrices. -{{{ switch to next slide, matrix operations }}} +{{{ switch to next slide, more matrix operations }}} To find out the transpose of a matrix we can do, :: @@ -120,9 +130,9 @@ Matrix name dot capital T will give the transpose of a matrix -{{{ switch to next slide, Euclidean norm of inverse of matrix }}} +{{{ switch to next slide, Frobenius norm of inverse of matrix }}} -Now let us try to find out the Euclidean norm of inverse of a 4 by 4 +Now let us try to find out the Frobenius norm of inverse of a 4 by 4 matrix, the matrix being, :: @@ -131,17 +141,17 @@ 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 -Euclidean norm or 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)``. +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 euclidean norm of the matrix ``im5`` can be found out as, +And the Frobenius norm of the matrix ``im5`` can be found out as, :: sum = 0 @@ -166,11 +176,11 @@ {{{ switch to slide the ``norm()`` method }}} -Well! to find the Euclidean norm and Infinity norm we have an even easier +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 Euclidean norm of the matrix im5, +``norm()``. Inorder to find out the Frobenius norm of the matrix im5, we do, :: diff -r 4bebfa8c9a0a -r c6d31837cb06 matrices/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/matrices/slides.org Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 matrices/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/matrices/slides.tex Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 other-type-of-plots/bar-chart-hatch.png Binary file other-type-of-plots/bar-chart-hatch.png has changed diff -r 4bebfa8c9a0a -r c6d31837cb06 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 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 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 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 other-type-of-plots/script.rst --- a/other-type-of-plots/script.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/other-type-of-plots/script.rst Wed Oct 13 11:15:37 2010 +0530 @@ -3,7 +3,7 @@ .. * scatter .. * pie chart .. * bar chart -.. * log +.. * loglog .. * illustration of other plots, matplotlib help =================== @@ -17,13 +17,12 @@ {{{ show the outline slide }}} In this tutorial we will cover scatter plot, pie chart, bar chart and -log plot. We will also see few other plots and also introduce you to +loglog plot. We will also see few other plots and also introduce you to the matplotlib help. - Let us start with scatter plot. -{{{ switch to the next slide }}} +{{{ switch to the next slide, scatter plot }}} In a scatter plot, the data is displayed as a collection of points, each having the value of one variable determining the position on the @@ -55,11 +54,14 @@ {{{ 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, +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())) + year,profit = + loadtxt('/home/fossee/other-plot/company-a-data.txt',dtype=type(int())) + +{{{ switch to next slide, ``scatter`` function }}} Now in-order to generate the scatter graph we will use the function ``scatter()`` @@ -75,9 +77,11 @@ problem to be tried out }}} Now here is a question for you to try out, plot the same data with red -diamonds. +diamonds markers. -**Clue** - *try scatter? in your ipython interpreter* +.. **Clue** - *try scatter? in your ipython interpreter* + +Pause here and solve the question before moving on. .. scatter(year,profit,color='r',marker='d') @@ -95,14 +99,16 @@ 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()``. The -first one the values and the next one the set of labels to be used in -the pie chart. +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 }}} @@ -111,7 +117,9 @@ same data with colors for each wedges as white, red, black, magenta, yellow, blue, green, cyan, yellow, magenta and blue respectively. -**Clue** - *try pie? in your ipython interpreter* +.. **Clue** - *try pie? in your ipython interpreter* + +Pause here and solve the question before moving on. .. pie(t,labels=s,colors=('w','r','k','m','y','b','g','c','y','m','b')) @@ -121,7 +129,7 @@ with rectangular bars with lengths proportional to the values that they represent. -{{{ switch to the slide showing the problem statement of third +{{{ switch to the slide showing the problem statement of fifth exercise question }}} Plot a bar chart representing the profit percentage of company A, with @@ -129,6 +137,8 @@ So let us reuse the data we have loaded from the file previously. +{{{ switch to the next slide, ``bar()`` function }}} + We can plot the bar chart using the function ``bar()``. :: @@ -143,13 +153,14 @@ Now here is a question for you to try, plot a bar chart which is not filled and which is hatched with 45\ :sup:`o` slanting lines as shown -in the image in the slide. +in the image in the slide. The data for the chart may be obtained from +the file ``company-a-data.txt``. -**Clue** - *try bar? in your ipython interpreter* +.. **Clue** - *try bar? in your ipython interpreter* .. bar(year,profit,fill=False,hatch='/') -{{{ switch to the slide which says about bar chart }}} +{{{ switch to the slide which says about log-log graph }}} Now let us move on to log-log plot. A log-log graph or log-log plot is a two-dimensional graph of numerical data that uses logarithmic scales @@ -170,6 +181,8 @@ x = linspace(1,20,100) y = 5*x**3 +{{{ switch to next slide, ``loglog()`` function }}} + Now we can plot the log-log chart using ``loglog()`` function, :: @@ -195,16 +208,12 @@ 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 +More plots can be seen at +matplotlib.sourceforge.net/users/screenshots.html and also at +matplotlib.sourceforge.net/gallery.html -{{{ browse through the site quickly }}} - -{{{ switch to recap slide }}} +{{{ switch to summary slide }}} Now we have come to the end of this tutorial. We have covered scatter plot, pie chart, bar chart, log-log plot and also saw few other plots diff -r 4bebfa8c9a0a -r c6d31837cb06 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 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 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 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 savefig/script.rst --- a/savefig/script.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/savefig/script.rst Wed Oct 13 11:15:37 2010 +0530 @@ -9,8 +9,16 @@ Savefig ======= -Hello and welcome to the tutorial. In this tutorial you will learn how -to save plots using Python. +{{{ 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 :: @@ -38,9 +46,11 @@ 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 +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') @@ -73,6 +83,8 @@ 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 - @@ -81,15 +93,19 @@ .. #[[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. +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`` :: @@ -105,10 +121,17 @@ 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. -Let us review what we have learned in this session! We have learned to -save plots in different formats using the function ``savefig()``. +{{{ 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 4bebfa8c9a0a -r c6d31837cb06 savefig/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/savefig/slides.org Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 savefig/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/savefig/slides.tex Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 using python modules/script.rst --- a/using python modules/script.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/using python modules/script.rst Wed Oct 13 11:15:37 2010 +0530 @@ -17,7 +17,8 @@ {{{ switch to next slide, outline slide }}} In this tutorial, we will see how to run python scripts from command -line, importing modules, importing scipy and pylab modules. +line, importing modules, importing scipy and pylab modules. And also +see the Python standard library. {{{ switch to next slide on executing python scripts from command line }}} @@ -48,6 +49,8 @@ {{{ open terminal and navigate to directory where hello.py was saved }}} +{{{ switch to next slide }}} + now run the Python script as, :: @@ -59,6 +62,8 @@ The syntax is python space filename. +{{{ switch to next slide, four plot problem }}} + Now recall the four plot problem where we plotted four plots in a single figure. Let us run that script from command line. @@ -87,6 +92,8 @@ So now let us try to fix the problem and run the script in command line, +{{{ switch to next slide, fix ``linspace`` problem }}} + add the following line as the first line in the script, {{{ add the line as first line in four_plot.py and save }}} :: @@ -100,6 +107,9 @@ Now it gave another error plot not defined, let us edit the file again and add the line below the line we just added, + +{{{ switch to next slide, fix ``plot`` problem }}} + {{{ add the line as second line in four_plot.py and save }}} :: @@ -115,6 +125,8 @@ We actually imported the required modules using the keyword ``import``. It could have also be done as, +{{{ switch to next slide, better way of fixing }}} + {{{ highlight the following in slide and say it loud }}} :: @@ -130,29 +142,26 @@ module then it will replace any existing functions with the same name in our name-space. +{{{ switch to next slide, Instead of ``*`` }}} + So let us modify four_plot.py as, {{{ delete the first two lines and add the following }}} :: from scipy import linspace, pi, sin - from pylab import plot, legend, annotate, title, show - from pylab import xlim, ylim + from pylab import plot, legend, annotate + from pylab import xlim, ylim, title, show + +Now let us try running the code again as, +:: + + python four_plot.py + +It works! In this method we actually imported the functions to the +current name-space, and there is another method of doing it. And that +is, {{{ switch to next slide }}} -it could also be done as, - -.. import scipy -.. import pylab -.. x = scipy.linspace(-5*scipy.pi, 5*scipy.pi, 500) -.. pylab.plot(x, x, 'b') -.. pylab.plot(x, -x, 'b') -.. pylab.plot(x, scipy.sin(x), 'g', linewidth=2) -.. pylab.plot(x, x*scipy.sin(x), 'r', linewidth=3) -.. pylab.legend(['x', '-x', 'sin(x)', 'xsin(x)']) -.. pylab.annotate('origin', xy = (0, 0)) -.. pylab.xlim(-5*scipy.pi, 5*scipy.pi) -.. pylab.ylim(-5*scipy.pi, 5*scipy.pi) - Notice that we use ``scipy.pi`` instead of just ``pi`` as in the previous method, and the functions are called as ``pylab.plot()`` and @@ -211,7 +220,7 @@ The modules pylab, scipy, Mayavi are not part of the standard python library. -{{{ switch to next slide, recap }}} +{{{ switch to next slide, summary }}} This brings us to the end of this tutorial, in this tutorial we learned running scripts from command line, learned about modules, saw diff -r 4bebfa8c9a0a -r c6d31837cb06 using python modules/slides.org --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/slides.org Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 using python modules/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/using python modules/slides.tex Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 using-sage/questions.rst --- a/using-sage/questions.rst Wed Oct 13 11:15:18 2010 +0530 +++ b/using-sage/questions.rst Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 using_sage_to_teach.rst --- a/using_sage_to_teach.rst Wed Oct 13 11:15:18 2010 +0530 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,48 +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 - -2D - * plot - * parametric_plot - * polygon - * line -3D - * plot3d - * parametric_plot3d -{{{ 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 4bebfa8c9a0a -r c6d31837cb06 writing_python_scripts.rst --- a/writing_python_scripts.rst Wed Oct 13 11:15:18 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 4bebfa8c9a0a -r c6d31837cb06 writing_python_scripts/questions.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/writing_python_scripts/questions.rst Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 writing_python_scripts/quickref.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/writing_python_scripts/quickref.tex Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 writing_python_scripts/script.rst --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/writing_python_scripts/script.rst Wed Oct 13 11:15:37 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 4bebfa8c9a0a -r c6d31837cb06 writing_python_scripts/slides.tex --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/writing_python_scripts/slides.tex Wed Oct 13 11:15:37 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}