diff options
author | Madhusudan.C.S | 2009-10-03 00:41:12 +0530 |
---|---|---|
committer | Madhusudan.C.S | 2009-10-03 00:41:12 +0530 |
commit | 4962e54370627e723248cd15db0ba638beb8b199 (patch) | |
tree | 6e2958fbff8cf653b3f55b0c5c758468f4c4cad6 /day1 | |
parent | d344106f89a1f9a19fa0070d8f0f752cec44c4be (diff) | |
download | workshops-more-scipy-4962e54370627e723248cd15db0ba638beb8b199.tar.gz workshops-more-scipy-4962e54370627e723248cd15db0ba638beb8b199.tar.bz2 workshops-more-scipy-4962e54370627e723248cd15db0ba638beb8b199.zip |
Added 4 tex slides for 4 sessions of Day 1 of the workshop.
Diffstat (limited to 'day1')
-rw-r--r-- | day1/Session-1.aux | 240 | ||||
-rw-r--r-- | day1/Session-1.log | 1623 | ||||
-rw-r--r-- | day1/Session-1.nav | 211 | ||||
-rw-r--r-- | day1/Session-1.out | 11 | ||||
-rw-r--r-- | day1/Session-1.pdf | bin | 0 -> 746718 bytes | |||
-rw-r--r-- | day1/Session-1.snm | 0 | ||||
-rwxr-xr-x | day1/Session-1.tex | 2752 | ||||
-rwxr-xr-x | day1/Session-1.tex~ | 2752 | ||||
-rw-r--r-- | day1/Session-1.toc | 13 | ||||
-rw-r--r-- | day1/Session-1.vrb | 6 | ||||
-rwxr-xr-x | day1/Session-2.tex | 2745 | ||||
-rwxr-xr-x | day1/Session-3.tex | 2745 | ||||
-rwxr-xr-x | day1/Session-4.tex | 2745 |
13 files changed, 15843 insertions, 0 deletions
diff --git a/day1/Session-1.aux b/day1/Session-1.aux new file mode 100644 index 0000000..3420adf --- /dev/null +++ b/day1/Session-1.aux @@ -0,0 +1,240 @@ +\relax +\ifx\hyper@anchor\@undefined +\global \let \oldcontentsline\contentsline +\gdef \contentsline#1#2#3#4{\oldcontentsline{#1}{#2}{#3}} +\global \let \oldnewlabel\newlabel +\gdef \newlabel#1#2{\newlabelxx{#1}#2} +\gdef \newlabelxx#1#2#3#4#5#6{\oldnewlabel{#1}{{#2}{#3}}} +\AtEndDocument{\let \contentsline\oldcontentsline +\let \newlabel\oldnewlabel} +\else +\global \let \hyper@last\relax +\fi + +\@writefile{toc}{\beamer@endinputifotherversion {3.07pt}} +\@writefile{nav}{\beamer@endinputifotherversion {3.07pt}} +\select@language{english} +\@writefile{toc}{\select@language{english}} +\@writefile{lof}{\select@language{english}} +\@writefile{lot}{\select@language{english}} +\@writefile{nav}{\headcommand {\slideentry {0}{0}{1}{1/1}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {1}{1}}} +\@writefile{nav}{\headcommand {\slideentry {0}{0}{2}{2/2}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {2}{2}}} +\@writefile{nav}{\headcommand {\slideentry {0}{0}{3}{3/3}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {3}{3}}} +\@writefile{toc}{\beamer@sectionintoc {1}{Agenda}{4}{0}{1}} +\@writefile{nav}{\headcommand {\sectionentry {1}{Agenda}{4}{Agenda}{0}}} +\@writefile{nav}{\headcommand {\beamer@sectionpages {1}{3}}} +\@writefile{nav}{\headcommand {\beamer@subsectionpages {1}{3}}} +\@writefile{nav}{\headcommand {\slideentry {1}{0}{4}{4/4}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {4}{4}}} +\@writefile{toc}{\beamer@sectionintoc {2}{Agenda}{5}{0}{2}} +\@writefile{nav}{\headcommand {\sectionentry {2}{Agenda}{5}{Agenda}{0}}} +\@writefile{nav}{\headcommand {\beamer@sectionpages {4}{4}}} +\@writefile{nav}{\headcommand {\beamer@subsectionpages {4}{4}}} +\@writefile{nav}{\headcommand {\slideentry {2}{0}{5}{5/5}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {5}{5}}} +\@writefile{nav}{\headcommand {\slideentry {2}{0}{6}{6/6}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {6}{6}}} +\@writefile{toc}{\beamer@sectionintoc {3}{Overview}{7}{0}{3}} +\@writefile{nav}{\headcommand {\sectionentry {3}{Overview}{7}{Overview}{0}}} +\@writefile{nav}{\headcommand {\beamer@sectionpages {5}{6}}} +\@writefile{nav}{\headcommand {\beamer@subsectionpages {5}{6}}} +\@writefile{nav}{\headcommand {\slideentry {3}{0}{7}{7/7}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {7}{7}}} +\@writefile{nav}{\headcommand {\slideentry {3}{0}{8}{8/8}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {8}{8}}} +\@writefile{nav}{\headcommand {\slideentry {3}{0}{9}{9/9}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {9}{9}}} +\@writefile{nav}{\headcommand {\slideentry {3}{0}{10}{10/10}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {10}{10}}} +\@writefile{nav}{\headcommand {\slideentry {3}{0}{11}{11/11}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {11}{11}}} +\@writefile{nav}{\headcommand {\slideentry {3}{0}{12}{12/12}{}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {12}{12}}} +\@writefile{toc}{\beamer@sectionintoc {4}{Python}{13}{0}{4}} +\@writefile{nav}{\headcommand {\sectionentry {4}{Python}{13}{Python}{0}}} +\@writefile{nav}{\headcommand {\beamer@sectionpages {7}{12}}} +\@writefile{nav}{\headcommand {\beamer@subsectionpages {7}{12}}} +\@writefile{toc}{\beamer@subsectionintoc {4}{1}{Getting Started}{13}{0}{4}} +\@writefile{nav}{\headcommand {\beamer@subsectionentry {0}{4}{1}{13}{Getting Started}}\headcommand {\beamer@subsectionpages {13}{12}}} +\@writefile{nav}{\headcommand {\slideentry {4}{1}{1}{13/13}{Getting Started}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {13}{13}}} +\@writefile{nav}{\headcommand {\slideentry {4}{1}{2}{14/14}{Getting Started}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {14}{14}}} +\@writefile{nav}{\headcommand {\slideentry {4}{1}{3}{15/15}{Getting Started}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {15}{15}}} +\@writefile{nav}{\headcommand {\slideentry {4}{1}{4}{16/16}{Getting Started}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {16}{16}}} +\@writefile{nav}{\headcommand {\slideentry {4}{1}{5}{17/17}{Getting Started}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {17}{17}}} +\@writefile{nav}{\headcommand {\slideentry {4}{1}{6}{18/18}{Getting Started}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {18}{18}}} +\@writefile{nav}{\headcommand {\slideentry {4}{1}{7}{19/20}{Getting Started}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {19}{20}}} +\@writefile{nav}{\headcommand {\slideentry {4}{1}{8}{21/21}{Getting Started}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {21}{21}}} +\@writefile{toc}{\beamer@subsectionintoc {4}{2}{Data types}{22}{0}{4}} +\@writefile{nav}{\headcommand {\beamer@subsectionentry {0}{4}{2}{22}{Data types}}\headcommand {\beamer@subsectionpages {13}{21}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{1}{22/22}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {22}{22}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{2}{23/23}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {23}{23}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{3}{24/24}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {24}{24}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{4}{25/25}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {25}{25}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{5}{26/26}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {26}{26}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{6}{27/27}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {27}{27}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{7}{28/29}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {28}{29}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{8}{30/30}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {30}{30}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{9}{31/31}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {31}{31}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{10}{32/32}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {32}{32}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{11}{33/33}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {33}{33}}} +\@writefile{nav}{\headcommand {\slideentry {4}{2}{12}{34/34}{Data types}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {34}{34}}} +\@writefile{toc}{\beamer@subsectionintoc {4}{3}{Control flow}{35}{0}{4}} +\@writefile{nav}{\headcommand {\beamer@subsectionentry {0}{4}{3}{35}{Control flow}}\headcommand {\beamer@subsectionpages {22}{34}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{1}{35/35}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {35}{35}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{2}{36/36}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {36}{36}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{3}{37/37}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {37}{37}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{4}{38/38}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {38}{38}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{5}{39/39}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {39}{39}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{6}{40/40}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {40}{40}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{7}{41/41}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {41}{41}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{8}{42/42}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {42}{42}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{9}{43/43}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {43}{43}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{10}{44/44}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {44}{44}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{11}{45/45}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {45}{45}}} +\@writefile{nav}{\headcommand {\slideentry {4}{3}{12}{46/47}{Control flow}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {46}{47}}} +\@writefile{toc}{\beamer@subsectionintoc {4}{4}{Functions}{48}{0}{4}} +\@writefile{nav}{\headcommand {\beamer@subsectionentry {0}{4}{4}{48}{Functions}}\headcommand {\beamer@subsectionpages {35}{47}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{1}{48/48}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {48}{48}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{2}{49/49}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {49}{49}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{3}{50/51}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {50}{51}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{4}{52/52}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {52}{52}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{5}{53/53}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {53}{53}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{6}{54/54}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {54}{54}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{7}{55/55}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {55}{55}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{8}{56/56}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {56}{56}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{9}{57/57}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {57}{57}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{10}{58/58}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {58}{58}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{11}{59/59}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {59}{59}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{12}{60/60}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {60}{60}}} +\@writefile{nav}{\headcommand {\slideentry {4}{4}{13}{61/61}{Functions}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {61}{61}}} +\@writefile{toc}{\beamer@subsectionintoc {4}{5}{Lists}{62}{0}{4}} +\@writefile{nav}{\headcommand {\beamer@subsectionentry {0}{4}{5}{62}{Lists}}\headcommand {\beamer@subsectionpages {48}{61}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{1}{62/62}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {62}{62}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{2}{63/63}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {63}{63}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{3}{64/64}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {64}{64}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{4}{65/65}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {65}{65}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{5}{66/67}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {66}{67}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{6}{68/68}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {68}{68}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{7}{69/69}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {69}{69}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{8}{70/70}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {70}{70}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{9}{71/71}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {71}{71}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{10}{72/72}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {72}{72}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{11}{73/73}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {73}{73}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{12}{74/74}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {74}{74}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{13}{75/75}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {75}{75}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{14}{76/76}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {76}{76}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{15}{77/77}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {77}{77}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{16}{78/78}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {78}{78}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{17}{79/79}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {79}{79}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{18}{80/80}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {80}{80}}} +\@writefile{nav}{\headcommand {\slideentry {4}{5}{19}{81/81}{Lists}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {81}{81}}} +\@writefile{toc}{\beamer@subsectionintoc {4}{6}{IO}{82}{0}{4}} +\@writefile{nav}{\headcommand {\beamer@subsectionentry {0}{4}{6}{82}{IO}}\headcommand {\beamer@subsectionpages {62}{81}}} +\@writefile{nav}{\headcommand {\slideentry {4}{6}{1}{82/82}{IO}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {82}{82}}} +\@writefile{nav}{\headcommand {\slideentry {4}{6}{2}{83/83}{IO}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {83}{83}}} +\@writefile{nav}{\headcommand {\slideentry {4}{6}{3}{84/84}{IO}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {84}{84}}} +\@writefile{nav}{\headcommand {\slideentry {4}{6}{4}{85/85}{IO}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {85}{85}}} +\@writefile{nav}{\headcommand {\slideentry {4}{6}{5}{86/86}{IO}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {86}{86}}} +\@writefile{nav}{\headcommand {\slideentry {4}{6}{6}{87/87}{IO}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {87}{87}}} +\@writefile{nav}{\headcommand {\slideentry {4}{6}{7}{88/88}{IO}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {88}{88}}} +\@writefile{toc}{\beamer@subsectionintoc {4}{7}{Modules}{89}{0}{4}} +\@writefile{nav}{\headcommand {\beamer@subsectionentry {0}{4}{7}{89}{Modules}}\headcommand {\beamer@subsectionpages {82}{88}}} +\@writefile{nav}{\headcommand {\slideentry {4}{7}{1}{89/89}{Modules}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {89}{89}}} +\@writefile{nav}{\headcommand {\slideentry {4}{7}{2}{90/90}{Modules}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {90}{90}}} +\@writefile{nav}{\headcommand {\slideentry {4}{7}{3}{91/91}{Modules}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {91}{91}}} +\@writefile{nav}{\headcommand {\slideentry {4}{7}{4}{92/92}{Modules}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {92}{92}}} +\@writefile{nav}{\headcommand {\slideentry {4}{7}{5}{93/93}{Modules}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {93}{93}}} +\@writefile{nav}{\headcommand {\slideentry {4}{7}{6}{94/94}{Modules}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {94}{94}}} +\@writefile{nav}{\headcommand {\slideentry {4}{7}{7}{95/95}{Modules}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {95}{95}}} +\@writefile{nav}{\headcommand {\slideentry {4}{7}{8}{96/96}{Modules}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {96}{96}}} +\@writefile{nav}{\headcommand {\slideentry {4}{7}{9}{97/97}{Modules}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {97}{97}}} +\@writefile{nav}{\headcommand {\slideentry {4}{7}{10}{98/98}{Modules}{0}}} +\@writefile{nav}{\headcommand {\beamer@framepages {98}{98}}} +\@writefile{nav}{\headcommand {\beamer@partpages {1}{98}}} +\@writefile{nav}{\headcommand {\beamer@subsectionpages {89}{98}}} +\@writefile{nav}{\headcommand {\beamer@sectionpages {13}{98}}} +\@writefile{nav}{\headcommand {\beamer@documentpages {98}}} +\@writefile{nav}{\headcommand {\def \inserttotalframenumber {93}}} diff --git a/day1/Session-1.log b/day1/Session-1.log new file mode 100644 index 0000000..70e3fda --- /dev/null +++ b/day1/Session-1.log @@ -0,0 +1,1623 @@ +This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6) (format=pdflatex 2009.8.17) 3 OCT 2009 00:15 +entering extended mode + %&-line parsing enabled. +**Session-1.tex +(./Session-1.tex +LaTeX2e <2005/12/01> +Babel <v3.8h> and hyphenation patterns for english, usenglishmax, dumylang, noh +yphenation, ukrainian, russian, bulgarian, loaded. +(/usr/share/texmf/tex/latex/beamer/base/beamer.cls +(/usr/share/texmf/tex/latex/beamer/base/beamerbasercs.sty +Package: beamerbasercs 2007/01/28 (rcs-revision 1.4) +) +Document Class: beamer 2007/03/11 cvs version 3.07 A class for typesetting pres +entations (rcs-revision 1.70) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasemodes.sty +Package: beamerbasemodes 2007/01/28 (rcs-revision 1.22) +\beamer@tempbox=\box26 +\beamer@tempcount=\count79 +\c@beamerpauses=\count80 + +(/usr/share/texmf/tex/latex/beamer/base/beamerbasedecode.sty +Package: beamerbasedecode 2007/01/28 (rcs-revision 1.20) +\beamer@slideinframe=\count81 +\beamer@minimum=\count82 +) +\beamer@commentbox=\box27 +\beamer@modecount=\count83 +) +\headheight=\dimen102 +\headdp=\dimen103 +\footheight=\dimen104 +\sidebarheight=\dimen105 +\beamer@tempdim=\dimen106 +\beamer@finalheight=\dimen107 +\beamer@animht=\dimen108 +\beamer@animdp=\dimen109 +\beamer@animwd=\dimen110 +\beamer@leftmargin=\dimen111 +\beamer@rightmargin=\dimen112 +\beamer@leftsidebar=\dimen113 +\beamer@rightsidebar=\dimen114 +\beamer@boxsize=\dimen115 +\beamer@vboxoffset=\dimen116 +\beamer@descdefault=\dimen117 +\beamer@descriptionwidth=\dimen118 +\beamer@lastskip=\skip41 +\beamer@areabox=\box28 +\beamer@animcurrent=\box29 +\beamer@animshowbox=\box30 +\beamer@sectionbox=\box31 +\beamer@logobox=\box32 +\beamer@linebox=\box33 +\beamer@sectioncount=\count84 +\beamer@subsubsectionmax=\count85 +\beamer@subsectionmax=\count86 +\beamer@sectionmax=\count87 +\beamer@totalheads=\count88 +\beamer@headcounter=\count89 +\beamer@partstartpage=\count90 +\beamer@sectionstartpage=\count91 +\beamer@subsectionstartpage=\count92 +\beamer@animationtempa=\count93 +\beamer@animationtempb=\count94 +\beamer@xpos=\count95 +\beamer@ypos=\count96 +\beamer@showpartnumber=\count97 +\beamer@currentsubsection=\count98 +\beamer@coveringdepth=\count99 +\beamer@sectionadjust=\count100 +\beamer@tocsectionnumber=\count101 + +(/usr/share/texmf/tex/latex/beamer/base/beamerbaseoptions.sty +Package: beamerbaseoptions 2007/01/28 (rcs-revision 1.8) + +(/usr/share/texmf-texlive/tex/latex/graphics/keyval.sty +Package: keyval 1999/03/16 v1.13 key=value parser (DPC) +\KV@toks@=\toks14 +)) +(/usr/share/texmf/tex/latex/pgf/basiclayer/pgfcore.sty +(/usr/share/texmf-texlive/tex/latex/graphics/graphicx.sty +Package: graphicx 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR) + +(/usr/share/texmf-texlive/tex/latex/graphics/graphics.sty +Package: graphics 2006/02/20 v1.0o Standard LaTeX Graphics (DPC,SPQR) + +(/usr/share/texmf-texlive/tex/latex/graphics/trig.sty +Package: trig 1999/03/16 v1.09 sin cos tan (DPC) +) +(/etc/texmf/tex/latex/config/graphics.cfg +File: graphics.cfg 2007/01/18 v1.5 graphics configuration of teTeX/TeXLive +) +Package graphics Info: Driver file: pdftex.def on input line 90. + +(/usr/share/texmf-texlive/tex/latex/pdftex-def/pdftex.def +File: pdftex.def 2007/01/08 v0.04d Graphics/color for pdfTeX +\Gread@gobject=\count102 +)) +\Gin@req@height=\dimen119 +\Gin@req@width=\dimen120 +) +(/usr/share/texmf/tex/latex/pgf/systemlayer/pgfsys.sty +(/usr/share/texmf/tex/latex/pgf/utilities/pgfrcs.sty +(/usr/share/texmf/tex/generic/pgf/utilities/pgfutil-common.tex +\pgfutil@everybye=\toks15 +) +(/usr/share/texmf/tex/generic/pgf/utilities/pgfutil-latex.def) +(/usr/share/texmf/tex/generic/pgf/utilities/pgfrcs.code.tex +Package: pgfrcs 2008/02/20 v2.00 (rcs-revision 1.21) +)) +(/usr/share/texmf/tex/generic/pgf/systemlayer/pgfsys.code.tex +Package: pgfsys 2008/02/07 v2.00 (rcs-revision 1.31) + +(/usr/share/texmf/tex/generic/pgf/utilities/pgfkeys.code.tex +\pgfkeys@pathtoks=\toks16 +\pgfkeys@temptoks=\toks17 +) +\pgf@x=\dimen121 +\pgf@y=\dimen122 +\pgf@xa=\dimen123 +\pgf@ya=\dimen124 +\pgf@xb=\dimen125 +\pgf@yb=\dimen126 +\pgf@xc=\dimen127 +\pgf@yc=\dimen128 +\c@pgf@counta=\count103 +\c@pgf@countb=\count104 +\c@pgf@countc=\count105 +\c@pgf@countd=\count106 + +(/usr/share/texmf/tex/generic/pgf/systemlayer/pgf.cfg +File: pgf.cfg 2008/01/13 (rcs-revision 1.6) +) +Package pgfsys Info: Driver file for pgf: pgfsys-pdftex.def on input line 885. + +(/usr/share/texmf/tex/generic/pgf/systemlayer/pgfsys-pdftex.def +File: pgfsys-pdftex.def 2007/12/20 (rcs-revision 1.20) + +(/usr/share/texmf/tex/generic/pgf/systemlayer/pgfsys-common-pdf.def +File: pgfsys-common-pdf.def 2007/12/17 (rcs-revision 1.8) +))) +(/usr/share/texmf/tex/generic/pgf/systemlayer/pgfsyssoftpath.code.tex +File: pgfsyssoftpath.code.tex 2008/01/23 (rcs-revision 1.6) +\pgfsyssoftpath@smallbuffer@items=\count107 +\pgfsyssoftpath@bigbuffer@items=\count108 +) +(/usr/share/texmf/tex/generic/pgf/systemlayer/pgfsysprotocol.code.tex +File: pgfsysprotocol.code.tex 2006/10/16 (rcs-revision 1.4) +)) +(/usr/share/texmf/tex/latex/xcolor/xcolor.sty +Package: xcolor 2007/01/21 v2.11 LaTeX color extensions (UK) + +(/etc/texmf/tex/latex/config/color.cfg +File: color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive +) +Package xcolor Info: Driver file: pdftex.def on input line 225. +Package xcolor Info: Model `cmy' substituted by `cmy0' on input line 1337. +Package xcolor Info: Model `hsb' substituted by `rgb' on input line 1341. +Package xcolor Info: Model `RGB' extended on input line 1353. +Package xcolor Info: Model `HTML' substituted by `rgb' on input line 1355. +Package xcolor Info: Model `Hsb' substituted by `hsb' on input line 1356. +Package xcolor Info: Model `tHsb' substituted by `hsb' on input line 1357. +Package xcolor Info: Model `HSB' substituted by `hsb' on input line 1358. +Package xcolor Info: Model `Gray' substituted by `gray' on input line 1359. +Package xcolor Info: Model `wave' substituted by `hsb' on input line 1360. +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcore.code.tex +Package: pgfcore 2008/01/15 v2.00 (rcs-revision 1.6) + +(/usr/share/texmf/tex/generic/pgf/math/pgfmath.code.tex +(/usr/share/texmf/tex/generic/pgf/math/pgfmathcalc.code.tex +(/usr/share/texmf/tex/generic/pgf/math/pgfmathutil.code.tex +\pgfmath@box=\box34 +) +(/usr/share/texmf/tex/generic/pgf/math/pgfmathparser.code.tex +\pgfmath@stack=\toks18 +\c@pgfmath@parsecounta=\count109 +\c@pgfmath@parsecountb=\count110 +\c@pgfmath@parsecountc=\count111 +\pgfmath@parsex=\dimen129 +) +(/usr/share/texmf/tex/generic/pgf/math/pgfmathoperations.code.tex +(/usr/share/texmf/tex/generic/pgf/math/pgfmathtrig.code.tex) +(/usr/share/texmf/tex/generic/pgf/math/pgfmathrnd.code.tex)) +(/usr/share/texmf/tex/generic/pgf/math/pgfmathbase.code.tex))) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcorepoints.code.tex +File: pgfcorepoints.code.tex 2008/02/03 (rcs-revision 1.13) +\pgf@picminx=\dimen130 +\pgf@picmaxx=\dimen131 +\pgf@picminy=\dimen132 +\pgf@picmaxy=\dimen133 +\pgf@pathminx=\dimen134 +\pgf@pathmaxx=\dimen135 +\pgf@pathminy=\dimen136 +\pgf@pathmaxy=\dimen137 +\pgf@xx=\dimen138 +\pgf@xy=\dimen139 +\pgf@yx=\dimen140 +\pgf@yy=\dimen141 +\pgf@zx=\dimen142 +\pgf@zy=\dimen143 +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcorepathconstruct.code.tex +File: pgfcorepathconstruct.code.tex 2008/02/13 (rcs-revision 1.14) +\pgf@path@lastx=\dimen144 +\pgf@path@lasty=\dimen145 +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcorepathusage.code.tex +File: pgfcorepathusage.code.tex 2008/01/23 (rcs-revision 1.11) +\pgf@shorten@end@additional=\dimen146 +\pgf@shorten@start@additional=\dimen147 +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcorescopes.code.tex +File: pgfcorescopes.code.tex 2008/01/15 (rcs-revision 1.26) +\pgfpic=\box35 +\pgf@hbox=\box36 +\pgf@layerbox@main=\box37 +\pgf@picture@serial@count=\count112 +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcoregraphicstate.code.tex +File: pgfcoregraphicstate.code.tex 2007/12/12 (rcs-revision 1.8) +\pgflinewidth=\dimen148 +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcoretransformations.code.tex +File: pgfcoretransformations.code.tex 2008/02/04 (rcs-revision 1.10) +\pgf@pt@x=\dimen149 +\pgf@pt@y=\dimen150 +\pgf@pt@temp=\dimen151 +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcorequick.code.tex +File: pgfcorequick.code.tex 2006/10/11 (rcs-revision 1.2) +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcoreobjects.code.tex +File: pgfcoreobjects.code.tex 2006/10/11 (rcs-revision 1.2) +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcorepathprocessing.code.tex +File: pgfcorepathprocessing.code.tex 2008/01/23 (rcs-revision 1.7) +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcorearrows.code.tex +File: pgfcorearrows.code.tex 2007/06/07 (rcs-revision 1.8) +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcoreshade.code.tex +File: pgfcoreshade.code.tex 2007/12/10 (rcs-revision 1.9) +\pgf@max=\dimen152 +\pgf@sys@shading@range@num=\count113 +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcoreimage.code.tex +File: pgfcoreimage.code.tex 2008/01/15 (rcs-revision 1.1) +\pgfexternal@startupbox=\box38 +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcorelayers.code.tex +File: pgfcorelayers.code.tex 2008/01/15 (rcs-revision 1.1) +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcoretransparency.code.tex +File: pgfcoretransparency.code.tex 2008/01/17 (rcs-revision 1.2) +) +(/usr/share/texmf/tex/generic/pgf/basiclayer/pgfcorepatterns.code.tex +File: pgfcorepatterns.code.tex 2008/01/15 (rcs-revision 1.1) +))) +(/usr/share/texmf/tex/latex/pgf/basiclayer/pgfbaseimage.sty + +Package pgf Warning: This package is obsolete and no longer needed on input lin +e 13. + +) (/usr/share/texmf/tex/latex/pgf/utilities/xxcolor.sty +Package: xxcolor 2003/10/24 ver 0.1 +\XC@nummixins=\count114 +\XC@countmixins=\count115 +) +(/usr/share/texmf-texlive/tex/latex/amsfonts/amssymb.sty +Package: amssymb 2002/01/22 v2.2d + +(/usr/share/texmf-texlive/tex/latex/amsfonts/amsfonts.sty +Package: amsfonts 2001/10/25 v2.2f +\@emptytoks=\toks19 +\symAMSa=\mathgroup4 +\symAMSb=\mathgroup5 +LaTeX Font Info: Overwriting math alphabet `\mathfrak' in version `bold' +(Font) U/euf/m/n --> U/euf/b/n on input line 132. +)) +(/usr/share/texmf-texlive/tex/latex/geometry/geometry.sty +Package: geometry 2002/07/08 v3.2 Page Geometry +\Gm@cnth=\count116 +\Gm@cntv=\count117 +\c@Gm@tempcnt=\count118 +\Gm@bindingoffset=\dimen153 +\Gm@wd@mp=\dimen154 +\Gm@odd@mp=\dimen155 +\Gm@even@mp=\dimen156 +\Gm@dimlist=\toks20 + +(/usr/share/texmf-texlive/tex/xelatex/xetexconfig/geometry.cfg)) +(/usr/share/texmf-texlive/tex/latex/hyperref/hyperref.sty +Package: hyperref 2007/02/07 v6.75r Hypertext links for LaTeX +\@linkdim=\dimen157 +\Hy@linkcounter=\count119 +\Hy@pagecounter=\count120 + +(/usr/share/texmf-texlive/tex/latex/hyperref/pd1enc.def +File: pd1enc.def 2007/02/07 v6.75r Hyperref: PDFDocEncoding definition (HO) +) +(/etc/texmf/tex/latex/config/hyperref.cfg +File: hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive +) +(/usr/share/texmf-texlive/tex/latex/oberdiek/kvoptions.sty +Package: kvoptions 2006/08/22 v2.4 Connects package keyval with LaTeX options ( +HO) +) +Package hyperref Info: Option `bookmarks' set `true' on input line 2238. +Package hyperref Info: Option `bookmarksopen' set `true' on input line 2238. +Package hyperref Info: Option `implicit' set `false' on input line 2238. +Package hyperref Info: Hyper figures OFF on input line 2288. +Package hyperref Info: Link nesting OFF on input line 2293. +Package hyperref Info: Hyper index ON on input line 2296. +Package hyperref Info: Plain pages OFF on input line 2303. +Package hyperref Info: Backreferencing OFF on input line 2308. + +Implicit mode OFF; no redefinition of LaTeX internals +Package hyperref Info: Bookmarks ON on input line 2444. +(/usr/share/texmf-texlive/tex/latex/ltxmisc/url.sty +\Urlmuskip=\muskip10 +Package: url 2005/06/27 ver 3.2 Verb mode for urls, etc. +) +LaTeX Info: Redefining \url on input line 2599. +\Fld@menulength=\count121 +\Field@Width=\dimen158 +\Fld@charsize=\dimen159 +\Choice@toks=\toks21 +\Field@toks=\toks22 +Package hyperref Info: Hyper figures OFF on input line 3102. +Package hyperref Info: Link nesting OFF on input line 3107. +Package hyperref Info: Hyper index ON on input line 3110. +Package hyperref Info: backreferencing OFF on input line 3117. +Package hyperref Info: Link coloring OFF on input line 3122. + + +Package hyperref Warning: Option `pdfpagelabels' is turned off +(hyperref) because \thepage is undefined. + +Hyperref stopped early +) +*hyperref using default driver hpdftex* +(/usr/share/texmf-texlive/tex/latex/hyperref/hpdftex.def +File: hpdftex.def 2007/02/07 v6.75r Hyperref driver for pdfTeX +\Fld@listcount=\count122 +) +(/usr/share/texmf-texlive/tex/latex/extsizes/size14.clo +File: size14.clo 1999/11/11 v1.4a NON-Standard LaTeX file (size option) +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasecompatibility.sty +Package: beamerbasecompatibility 2007/01/28 (rcs-revision 1.63) +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasefont.sty +Package: beamerbasefont 2007/01/28 (rcs-revision 1.16) +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasemisc.sty +Package: beamerbasemisc 2007/01/28 (rcs-revision 1.24) +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasetwoscreens.sty +Package: beamerbasetwoscreens 2007/01/28 (rcs-revision 1.7) +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbaseoverlay.sty +Package: beamerbaseoverlay 2007/01/28 (rcs-revision 1.50) +\beamer@argscount=\count123 +\beamer@lastskipcover=\skip42 +\beamer@trivlistdepth=\count124 +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasetitle.sty +Package: beamerbasetitle 2007/01/28 (rcs-revision 1.25) +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasesection.sty +Package: beamerbasesection 2007/01/28 (rcs-revision 1.21) +\c@lecture=\count125 +\c@part=\count126 +\c@section=\count127 +\c@subsection=\count128 +\c@subsubsection=\count129 +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbaseframe.sty +Package: beamerbaseframe 2007/01/28 (rcs-revision 1.60) +\beamer@framebox=\box39 +\beamer@frametitlebox=\box40 +\beamer@zoombox=\box41 +\beamer@zoomcount=\count130 +\beamer@zoomframecount=\count131 +\beamer@frametextheight=\dimen160 +\c@subsectionslide=\count132 +\beamer@frametopskip=\skip43 +\beamer@framebottomskip=\skip44 +\beamer@frametopskipautobreak=\skip45 +\beamer@framebottomskipautobreak=\skip46 +\beamer@envbody=\toks23 +\c@framenumber=\count133 +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbaseverbatim.sty +Package: beamerbaseverbatim 2007/01/28 (rcs-revision 1.8) +\beamer@verbatimfileout=\write3 +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbaseframesize.sty +Package: beamerbaseframesize 2007/01/28 (rcs-revision 1.18) +\beamer@splitbox=\box42 +\beamer@autobreakcount=\count134 +\beamer@autobreaklastheight=\dimen161 +\beamer@frametitletoks=\toks24 +\beamer@framesubtitletoks=\toks25 +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbaseframecomponents.sty +Package: beamerbaseframecomponents 2007/01/28 (rcs-revision 1.41) +\beamer@footins=\box43 +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasecolor.sty +Package: beamerbasecolor 2007/01/28 (rcs-revision 1.42) +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasenotes.sty +Package: beamerbasenotes 2007/01/28 (rcs-revision 1.23) +\beamer@frameboxcopy=\box44 +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasetoc.sty +Package: beamerbasetoc 2007/01/28 (rcs-revision 1.21) +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasetemplates.sty +Package: beamerbasetemplates 2007/01/28 (rcs-revision 1.51) +\beamer@sbttoks=\toks26 + +(/usr/share/texmf/tex/latex/beamer/base/beamerbaseauxtemplates.sty +Package: beamerbaseauxtemplates 2007/01/28 (rcs-revision 1.28) + +(/usr/share/texmf/tex/latex/beamer/base/beamerbaseboxes.sty +Package: beamerbaseboxes 2007/03/11 (rcs-revision 1.32) +\bmb@box=\box45 +\bmb@colorbox=\box46 +\bmb@boxshadow=\box47 +\bmb@boxshadowball=\box48 +\bmb@boxshadowballlarge=\box49 +\bmb@temp=\dimen162 +\bmb@dima=\dimen163 +\bmb@dimb=\dimen164 +\bmb@prevheight=\dimen165 +) +\beamer@blockheadheight=\dimen166 +)) +(/usr/share/texmf/tex/latex/beamer/base/beamerbaselocalstructure.sty +Package: beamerbaselocalstructure 2007/01/28 (rcs-revision 1.53) + +(/usr/share/texmf-texlive/tex/latex/tools/enumerate.sty +Package: enumerate 1999/03/05 v3.00 enumerate extensions (DPC) +\@enLab=\toks27 +) +\c@figure=\count135 +\c@table=\count136 +\abovecaptionskip=\skip47 +\belowcaptionskip=\skip48 +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasenavigation.sty +Package: beamerbasenavigation 2007/01/28 (rcs-revision 1.36) +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasetheorems.sty +Package: beamerbasetheorems 2007/01/28 (rcs-revision 1.10) + +(/usr/share/texmf-texlive/tex/latex/amsmath/amsmath.sty +Package: amsmath 2000/07/18 v2.13 AMS math features +\@mathmargin=\skip49 + +For additional information on amsmath, use the `?' option. +(/usr/share/texmf-texlive/tex/latex/amsmath/amstext.sty +Package: amstext 2000/06/29 v2.01 + +(/usr/share/texmf-texlive/tex/latex/amsmath/amsgen.sty +File: amsgen.sty 1999/11/30 v2.0 +\@emptytoks=\toks28 +\ex@=\dimen167 +)) +(/usr/share/texmf-texlive/tex/latex/amsmath/amsbsy.sty +Package: amsbsy 1999/11/29 v1.2d +\pmbraise@=\dimen168 +) +(/usr/share/texmf-texlive/tex/latex/amsmath/amsopn.sty +Package: amsopn 1999/12/14 v2.01 operator names +) +\inf@bad=\count137 +LaTeX Info: Redefining \frac on input line 211. +\uproot@=\count138 +\leftroot@=\count139 +LaTeX Info: Redefining \overline on input line 307. +\classnum@=\count140 +\DOTSCASE@=\count141 +LaTeX Info: Redefining \ldots on input line 379. +LaTeX Info: Redefining \dots on input line 382. +LaTeX Info: Redefining \cdots on input line 467. +\Mathstrutbox@=\box50 +\strutbox@=\box51 +\big@size=\dimen169 +LaTeX Font Info: Redeclaring font encoding OML on input line 567. +LaTeX Font Info: Redeclaring font encoding OMS on input line 568. +\macc@depth=\count142 +\c@MaxMatrixCols=\count143 +\dotsspace@=\muskip11 +\c@parentequation=\count144 +\dspbrk@lvl=\count145 +\tag@help=\toks29 +\row@=\count146 +\column@=\count147 +\maxfields@=\count148 +\andhelp@=\toks30 +\eqnshift@=\dimen170 +\alignsep@=\dimen171 +\tagshift@=\dimen172 +\tagwidth@=\dimen173 +\totwidth@=\dimen174 +\lineht@=\dimen175 +\@envbody=\toks31 +\multlinegap=\skip50 +\multlinetaggap=\skip51 +\mathdisplay@stack=\toks32 +LaTeX Info: Redefining \[ on input line 2666. +LaTeX Info: Redefining \] on input line 2667. +) +(/usr/share/texmf-texlive/tex/latex/amscls/amsthm.sty +Package: amsthm 2004/08/06 v2.20 +\thm@style=\toks33 +\thm@bodyfont=\toks34 +\thm@headfont=\toks35 +\thm@notefont=\toks36 +\thm@headpunct=\toks37 +\thm@preskip=\skip52 +\thm@postskip=\skip53 +\thm@headsep=\skip54 +\dth@everypar=\toks38 +) +\c@theorem=\count149 +) +(/usr/share/texmf/tex/latex/beamer/base/beamerbasethemes.sty +Package: beamerbasethemes 2007/01/28 (rcs-revision 1.10) +) +(/usr/share/texmf/tex/latex/beamer/themes/theme/beamerthemedefault.sty +Package: beamerthemedefault 2007/01/28 (rcs-revision 1.7) + +(/usr/share/texmf/tex/latex/beamer/themes/font/beamerfontthemedefault.sty +Package: beamerfontthemedefault 2007/01/28 (rcs-revision 1.13) +) +(/usr/share/texmf/tex/latex/beamer/themes/color/beamercolorthemedefault.sty +Package: beamercolorthemedefault 2007/01/28 (rcs-revision 1.28) +) +(/usr/share/texmf/tex/latex/beamer/themes/inner/beamerinnerthemedefault.sty +Package: beamerinnerthemedefault 2007/01/28 (rcs-revision 1.20) +\beamer@dima=\dimen176 +\beamer@dimb=\dimen177 +) +(/usr/share/texmf/tex/latex/beamer/themes/outer/beamerouterthemedefault.sty +Package: beamerouterthemedefault 2007/01/28 (rcs-revision 1.14) +))) +(/usr/share/texmf/tex/latex/beamer/themes/theme/beamerthemeWarsaw.sty +Package: beamerthemeWarsaw 2007/01/28 (rcs-revision 1.9) + +(/usr/share/texmf/tex/latex/beamer/themes/inner/beamerinnerthemerounded.sty +Package: beamerinnerthemerounded 2007/01/28 (rcs-revision 1.5) +) +(/usr/share/texmf/tex/latex/beamer/themes/outer/beamerouterthemeshadow.sty +Package: beamerouterthemeshadow 2007/01/28 (rcs-revision 1.9) + +(/usr/share/texmf/tex/latex/beamer/themes/outer/beamerouterthemesplit.sty +Package: beamerouterthemesplit 2007/01/28 (rcs-revision 1.5) +)) +(/usr/share/texmf/tex/latex/beamer/themes/color/beamercolorthemeorchid.sty +Package: beamercolorthemeorchid 2007/01/28 (rcs-revision 1.3) +) +(/usr/share/texmf/tex/latex/beamer/themes/color/beamercolorthemewhale.sty +Package: beamercolorthemewhale 2007/01/28 (rcs-revision 1.4) +)) +(/usr/share/texmf-texlive/tex/generic/babel/babel.sty +Package: babel 2005/11/23 v3.8h The Babel package + +(/usr/share/texmf-texlive/tex/generic/babel/english.ldf +Language: english 2005/03/30 v3.3o English support from the babel system + +(/usr/share/texmf-texlive/tex/generic/babel/babel.def +File: babel.def 2005/11/23 v3.8h Babel common definitions +LaTeX Info: Redefining \textlatin on input line 82. +\babel@savecnt=\count150 +\U@D=\dimen178 +) +\l@british = a dialect from \language\l@english +\l@UKenglish = a dialect from \language\l@english +\l@canadian = a dialect from \language\l@american +\l@australian = a dialect from \language\l@british +\l@newzealand = a dialect from \language\l@british +)) +(/usr/share/texmf-texlive/tex/latex/base/inputenc.sty +Package: inputenc 2006/05/05 v1.1b Input encoding file +\inpenc@prehook=\toks39 +\inpenc@posthook=\toks40 + +(/usr/share/texmf-texlive/tex/latex/base/latin1.def +File: latin1.def 2006/05/05 v1.1b Input encoding file +)) +(/usr/share/texmf-texlive/tex/latex/base/fontenc.sty +Package: fontenc 2005/09/27 v1.99g Standard LaTeX package + +(/usr/share/texmf-texlive/tex/latex/base/t1enc.def +File: t1enc.def 2005/09/27 v1.99g Standard LaTeX file +LaTeX Font Info: Redeclaring font encoding T1 on input line 43. +)) +(/usr/share/texmf-texlive/tex/latex/ae/ae.sty +Package: ae 2001/02/12 1.3 Almost European Computer Modern + +(/usr/share/texmf-texlive/tex/latex/base/fontenc.sty +Package: fontenc 2005/09/27 v1.99g Standard LaTeX package + +(/usr/share/texmf-texlive/tex/latex/base/t1enc.def +File: t1enc.def 2005/09/27 v1.99g Standard LaTeX file +LaTeX Font Info: Redeclaring font encoding T1 on input line 43. +) +LaTeX Font Info: Try loading font information for T1+aer on input line 100. + +(/usr/share/texmf-texlive/tex/latex/ae/t1aer.fd +File: t1aer.fd 1997/11/16 Font definitions for T1/aer. +))) +(/usr/share/texmf-texlive/tex/latex/ae/aecompl.sty +Package: aecompl 1998/07/23 0.9 T1 Complements for AE fonts (D. Roegel) +) +(/usr/share/texmf-texlive/tex/latex/psnfss/mathpazo.sty +Package: mathpazo 2005/04/12 PSNFSS-v9.2a Palatino w/ Pazo Math (D.Puga, WaS) +\symupright=\mathgroup6 +) +(/usr/share/texmf-texlive/tex/latex/psnfss/courier.sty +Package: courier 2005/04/12 PSNFSS-v9.2a (WaS) +) +(/usr/share/texmf-texlive/tex/latex/euler/euler.sty +Package: euler 1995/03/05 v2.5 + +Package: `euler' v2.5 <1995/03/05> (FJ and FMi) +LaTeX Font Info: Redeclaring symbol font `letters' on input line 35. + +LaTeX Font Warning: Encoding `OML' has changed to `U' for symbol font +(Font) `letters' in the math version `normal' on input line 35. + +LaTeX Font Info: Overwriting symbol font `letters' in version `normal' +(Font) OML/zplm/m/it --> U/eur/m/n on input line 35. + +LaTeX Font Warning: Encoding `OML' has changed to `U' for symbol font +(Font) `letters' in the math version `bold' on input line 35. + +LaTeX Font Info: Overwriting symbol font `letters' in version `bold' +(Font) OML/zplm/b/it --> U/eur/m/n on input line 35. +LaTeX Font Info: Overwriting symbol font `letters' in version `bold' +(Font) U/eur/m/n --> U/eur/b/n on input line 36. +LaTeX Font Info: Redeclaring math symbol \Gamma on input line 47. +LaTeX Font Info: Redeclaring math symbol \Delta on input line 48. +LaTeX Font Info: Redeclaring math symbol \Theta on input line 49. +LaTeX Font Info: Redeclaring math symbol \Lambda on input line 50. +LaTeX Font Info: Redeclaring math symbol \Xi on input line 51. +LaTeX Font Info: Redeclaring math symbol \Pi on input line 52. +LaTeX Font Info: Redeclaring math symbol \Sigma on input line 53. +LaTeX Font Info: Redeclaring math symbol \Upsilon on input line 54. +LaTeX Font Info: Redeclaring math symbol \Phi on input line 55. +LaTeX Font Info: Redeclaring math symbol \Psi on input line 56. +LaTeX Font Info: Redeclaring math symbol \Omega on input line 57. +\symEulerFraktur=\mathgroup7 +LaTeX Font Info: Overwriting symbol font `EulerFraktur' in version `bold' +(Font) U/euf/m/n --> U/euf/b/n on input line 63. +LaTeX Font Info: Redeclaring math alphabet \mathfrak on input line 64. +LaTeX Info: Redefining \oldstylenums on input line 85. +\symEulerScript=\mathgroup8 +LaTeX Font Info: Overwriting symbol font `EulerScript' in version `bold' +(Font) U/eus/m/n --> U/eus/b/n on input line 93. +LaTeX Font Info: Redeclaring math symbol \aleph on input line 97. +LaTeX Font Info: Redeclaring math symbol \Re on input line 98. +LaTeX Font Info: Redeclaring math symbol \Im on input line 99. +LaTeX Font Info: Redeclaring math delimiter \vert on input line 101. +LaTeX Font Info: Redeclaring math delimiter \backslash on input line 103. +LaTeX Font Info: Redeclaring math symbol \neg on input line 106. +LaTeX Font Info: Redeclaring math symbol \wedge on input line 108. +LaTeX Font Info: Redeclaring math symbol \vee on input line 110. +LaTeX Font Info: Redeclaring math symbol \setminus on input line 112. +LaTeX Font Info: Redeclaring math symbol \sim on input line 113. +LaTeX Font Info: Redeclaring math symbol \mid on input line 114. +LaTeX Font Info: Redeclaring math delimiter \arrowvert on input line 116. +LaTeX Font Info: Redeclaring math symbol \mathsection on input line 117. +\symEulerExtension=\mathgroup9 +LaTeX Font Info: Redeclaring math symbol \coprod@ on input line 125. +LaTeX Font Info: Redeclaring math symbol \prod@ on input line 125. +LaTeX Font Info: Redeclaring math symbol \sum@ on input line 125. +LaTeX Font Info: Redeclaring math symbol \intop on input line 130. +LaTeX Font Info: Redeclaring math symbol \ointop on input line 131. +LaTeX Font Info: Redeclaring math symbol \braceld on input line 132. +LaTeX Font Info: Redeclaring math symbol \bracerd on input line 133. +LaTeX Font Info: Redeclaring math symbol \bracelu on input line 134. +LaTeX Font Info: Redeclaring math symbol \braceru on input line 135. +LaTeX Font Info: Redeclaring math symbol \infty on input line 136. +LaTeX Font Info: Redeclaring math symbol \nearrow on input line 153. +LaTeX Font Info: Redeclaring math symbol \searrow on input line 154. +LaTeX Font Info: Redeclaring math symbol \nwarrow on input line 155. +LaTeX Font Info: Redeclaring math symbol \swarrow on input line 156. +LaTeX Font Info: Redeclaring math symbol \Leftrightarrow on input line 157. +LaTeX Font Info: Redeclaring math symbol \Leftarrow on input line 158. +LaTeX Font Info: Redeclaring math symbol \Rightarrow on input line 159. +LaTeX Font Info: Redeclaring math symbol \leftrightarrow on input line 160. +LaTeX Font Info: Redeclaring math symbol \leftarrow on input line 161. +LaTeX Font Info: Redeclaring math symbol \rightarrow on input line 163. +LaTeX Font Info: Redeclaring math delimiter \uparrow on input line 166. +LaTeX Font Info: Redeclaring math delimiter \downarrow on input line 168. +LaTeX Font Info: Redeclaring math delimiter \updownarrow on input line 170. +LaTeX Font Info: Redeclaring math delimiter \Uparrow on input line 172. +LaTeX Font Info: Redeclaring math delimiter \Downarrow on input line 174. +LaTeX Font Info: Redeclaring math delimiter \Updownarrow on input line 176. +LaTeX Font Info: Redeclaring math symbol \leftharpoonup on input line 177. +LaTeX Font Info: Redeclaring math symbol \leftharpoondown on input line 178. + +LaTeX Font Info: Redeclaring math symbol \rightharpoonup on input line 179. +LaTeX Font Info: Redeclaring math symbol \rightharpoondown on input line 180 +. +LaTeX Font Info: Redeclaring math delimiter \lbrace on input line 182. +LaTeX Font Info: Redeclaring math delimiter \rbrace on input line 184. +\symcmmigroup=\mathgroup10 +LaTeX Font Info: Overwriting symbol font `cmmigroup' in version `bold' +(Font) OML/cmm/m/it --> OML/cmm/b/it on input line 200. +LaTeX Font Info: Redeclaring math accent \vec on input line 201. +LaTeX Font Info: Redeclaring math symbol \triangleleft on input line 202. +LaTeX Font Info: Redeclaring math symbol \triangleright on input line 203. +LaTeX Font Info: Redeclaring math symbol \star on input line 204. +LaTeX Font Info: Redeclaring math symbol \lhook on input line 205. +LaTeX Font Info: Redeclaring math symbol \rhook on input line 206. +LaTeX Font Info: Redeclaring math symbol \flat on input line 207. +LaTeX Font Info: Redeclaring math symbol \natural on input line 208. +LaTeX Font Info: Redeclaring math symbol \sharp on input line 209. +LaTeX Font Info: Redeclaring math symbol \smile on input line 210. +LaTeX Font Info: Redeclaring math symbol \frown on input line 211. +LaTeX Font Info: Redeclaring math accent \grave on input line 245. +LaTeX Font Info: Redeclaring math accent \acute on input line 246. +LaTeX Font Info: Redeclaring math accent \tilde on input line 247. +LaTeX Font Info: Redeclaring math accent \ddot on input line 248. +LaTeX Font Info: Redeclaring math accent \check on input line 249. +LaTeX Font Info: Redeclaring math accent \breve on input line 250. +LaTeX Font Info: Redeclaring math accent \bar on input line 251. +LaTeX Font Info: Redeclaring math accent \dot on input line 252. +LaTeX Font Info: Redeclaring math accent \hat on input line 254. +) (/usr/share/texmf-texlive/tex/latex/psnfss/helvet.sty +Package: helvet 2005/04/12 PSNFSS-v9.2a (WaS) +) +(/usr/share/texmf-texlive/tex/latex/listings/listings.sty +\lst@mode=\count151 +\lst@gtempboxa=\box52 +\lst@token=\toks41 +\lst@length=\count152 +\lst@currlwidth=\dimen179 +\lst@column=\count153 +\lst@pos=\count154 +\lst@lostspace=\dimen180 +\lst@width=\dimen181 +\lst@newlines=\count155 +\lst@lineno=\count156 +\c@lstlisting=\count157 +\lst@maxwidth=\dimen182 + +(/usr/share/texmf-texlive/tex/latex/listings/lstpatch.sty +File: lstpatch.sty 2004/10/17 1.3b (Carsten Heinz) +) +(/usr/share/texmf-texlive/tex/latex/listings/lstmisc.sty +File: lstmisc.sty 2004/09/07 1.3 (Carsten Heinz) +\c@lstnumber=\count158 +\lst@skipnumbers=\count159 +\lst@framebox=\box53 +) +(/usr/share/texmf-texlive/tex/latex/listings/listings.cfg +File: listings.cfg 2004/09/05 1.3 listings configuration +)) +Package: listings 2004/10/17 1.3b (Carsten Heinz) + +(/usr/share/texmf-texlive/tex/latex/listings/lstlang1.sty +File: lstlang1.sty 2004/09/05 1.3 listings language file +) +\c@time=\count160 + + +Package hyperref Warning: Token not allowed in a PDFDocEncoded string, +(hyperref) removing `\\' on input line 78. + +(./Session-1.aux) +\openout1 = `Session-1.aux'. + +LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 107. +LaTeX Font Info: ... okay on input line 107. +LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 107. +LaTeX Font Info: ... okay on input line 107. +LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 107. +LaTeX Font Info: ... okay on input line 107. +LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 107. +LaTeX Font Info: ... okay on input line 107. +LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 107. +LaTeX Font Info: ... okay on input line 107. +LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 107. +LaTeX Font Info: ... okay on input line 107. +LaTeX Font Info: Checking defaults for PD1/pdf/m/n on input line 107. +LaTeX Font Info: ... okay on input line 107. +LaTeX Font Info: Try loading font information for T1+phv on input line 107. + (/usr/share/texmf-texlive/tex/latex/psnfss/t1phv.fd +File: t1phv.fd 2001/06/04 scalable font definitions for T1/phv. +) +LaTeX Font Info: Font shape `T1/phv/m/n' will be +(Font) scaled to size 13.67995pt on input line 107. + +(/usr/share/texmf/tex/context/base/supp-pdf.tex +[Loading MPS to PDF converter (version 2006.09.02).] +\scratchcounter=\count161 +\scratchdimen=\dimen183 +\scratchbox=\box54 +\nofMPsegments=\count162 +\nofMParguments=\count163 +\everyMPshowfont=\toks42 +\MPscratchCnt=\count164 +\MPscratchDim=\dimen184 +\MPnumerator=\count165 +\everyMPtoPDFconversion=\toks43 +) +-------------------- Geometry parameters +paper: user defined +landscape: -- +twocolumn: -- +twoside: -- +asymmetric: -- +h-parts: 28.45274pt, 307.28987pt, 28.45274pt +v-parts: 0.0pt, 273.14662pt, 0.0pt +hmarginratio: -- +vmarginratio: -- +lines: -- +heightrounded: -- +bindingoffset: 0.0pt +truedimen: -- +includehead: true +includefoot: true +includemp: -- +driver: pdftex +-------------------- Page layout dimensions and switches +\paperwidth 364.19536pt +\paperheight 273.14662pt +\textwidth 307.28987pt +\textheight 244.6939pt +\oddsidemargin -43.81725pt +\evensidemargin -43.81725pt +\topmargin -72.26999pt +\headheight 14.22636pt +\headsep 0.0pt +\footskip 14.22636pt +\marginparwidth 4.0pt +\marginparsep 10.0pt +\columnsep 10.0pt +\skip\footins 12.0pt plus 4.0pt minus 2.0pt +\hoffset 0.0pt +\voffset 0.0pt +\mag 1000 + +(1in=72.27pt, 1cm=28.45pt) +----------------------- +Package hyperref Info: Link coloring OFF on input line 107. + (/usr/share/texmf-texlive/tex/latex/hyperref/nameref.sty +Package: nameref 2006/12/27 v2.28 Cross-referencing by name of section + +(/usr/share/texmf-texlive/tex/latex/oberdiek/refcount.sty +Package: refcount 2006/02/20 v3.0 Data extraction from references (HO) +) +\c@section@level=\count166 +) +LaTeX Info: Redefining \ref on input line 107. +LaTeX Info: Redefining \pageref on input line 107. + (./Session-1.out) +(./Session-1.out) +\@outlinefile=\write4 +\openout4 = `Session-1.out'. + +LaTeX Font Info: Overwriting symbol font `operators' in version `normal' +(Font) OT1/ppl/m/n --> OT1/cmss/m/n on input line 107. +LaTeX Font Info: Overwriting symbol font `operators' in version `bold' +(Font) OT1/ppl/b/n --> OT1/cmss/bx/n on input line 107. +\symnumbers=\mathgroup11 +\sympureletters=\mathgroup12 +LaTeX Font Info: Overwriting math alphabet `\mathrm' in version `normal' +(Font) OT1/cmss/m/n --> T1/ppl/m/n on input line 107. +LaTeX Font Info: Redeclaring math alphabet \mathbf on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathbf' in version `normal' +(Font) OT1/zplm/b/n --> T1/phv/bx/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathbf' in version `bold' +(Font) OT1/zplm/b/n --> T1/phv/bx/n on input line 107. +LaTeX Font Info: Redeclaring math alphabet \mathsf on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathsf' in version `normal' +(Font) OT1/cmss/m/n --> T1/phv/m/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathsf' in version `bold' +(Font) OT1/cmss/bx/n --> T1/phv/m/n on input line 107. +LaTeX Font Info: Redeclaring math alphabet \mathit on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathit' in version `normal' +(Font) OT1/ppl/m/it --> T1/phv/m/it on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathit' in version `bold' +(Font) OT1/ppl/b/it --> T1/phv/m/it on input line 107. +LaTeX Font Info: Redeclaring math alphabet \mathtt on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathtt' in version `normal' +(Font) OT1/cmtt/m/n --> T1/pcr/m/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathtt' in version `bold' +(Font) OT1/cmtt/m/n --> T1/pcr/m/n on input line 107. +LaTeX Font Info: Overwriting symbol font `numbers' in version `bold' +(Font) T1/phv/m/n --> T1/phv/bx/n on input line 107. +LaTeX Font Info: Overwriting symbol font `pureletters' in version `bold' +(Font) T1/phv/m/it --> T1/phv/bx/it on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathrm' in version `bold' +(Font) OT1/cmss/bx/n --> T1/ppl/bx/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathbf' in version `bold' +(Font) T1/phv/bx/n --> T1/phv/bx/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathsf' in version `bold' +(Font) T1/phv/m/n --> T1/phv/bx/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathit' in version `bold' +(Font) T1/phv/m/it --> T1/phv/bx/it on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathtt' in version `bold' +(Font) T1/pcr/m/n --> T1/pcr/bx/n on input line 107. +LaTeX Font Info: Redeclaring symbol font `operators' on input line 107. + + +LaTeX Font Warning: Encoding `OT1' has changed to `T1' for symbol font +(Font) `operators' in the math version `normal' on input line 107. + + +LaTeX Font Info: Overwriting symbol font `operators' in version `normal' +(Font) OT1/cmss/m/n --> T1/ppl/m/n on input line 107. + +LaTeX Font Warning: Encoding `OT1' has changed to `T1' for symbol font +(Font) `operators' in the math version `bold' on input line 107. + +LaTeX Font Info: Overwriting symbol font `operators' in version `bold' +(Font) OT1/cmss/bx/n --> T1/ppl/m/n on input line 107. +LaTeX Font Info: Overwriting symbol font `operators' in version `bold' +(Font) T1/ppl/m/n --> T1/ppl/bx/n on input line 107. +LaTeX Font Info: Redeclaring math alphabet \mathbf on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathbf' in version `normal' +(Font) T1/phv/bx/n --> T1/ppl/bx/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathbf' in version `bold' +(Font) T1/phv/bx/n --> T1/ppl/bx/n on input line 107. +LaTeX Font Info: Redeclaring math alphabet \mathsf on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathsf' in version `normal' +(Font) T1/phv/m/n --> T1/phv/m/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathsf' in version `bold' +(Font) T1/phv/bx/n --> T1/phv/m/n on input line 107. +LaTeX Font Info: Redeclaring math alphabet \mathit on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathit' in version `normal' +(Font) T1/phv/m/it --> T1/ppl/m/it on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathit' in version `bold' +(Font) T1/phv/bx/it --> T1/ppl/m/it on input line 107. +LaTeX Font Info: Redeclaring math alphabet \mathtt on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathtt' in version `normal' +(Font) T1/pcr/m/n --> T1/pcr/m/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathtt' in version `bold' +(Font) T1/pcr/bx/n --> T1/pcr/m/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathsf' in version `bold' +(Font) T1/phv/m/n --> T1/phv/bx/n on input line 107. +LaTeX Font Info: Overwriting math alphabet `\mathit' in version `bold' +(Font) T1/ppl/m/it --> T1/ppl/bx/it on input line 107. +(./Session-1.nav) +LaTeX Font Info: Font shape `T1/phv/m/n' will be +(Font) scaled to size 5.69998pt on input line 107. +LaTeX Font Info: Font shape `T1/phv/m/n' will be +(Font) scaled to size 19.70294pt on input line 111. +LaTeX Font Info: Font shape `T1/phv/m/n' will be +(Font) scaled to size 7.59998pt on input line 111. +LaTeX Font Info: Font shape `T1/phv/m/n' will be +(Font) scaled to size 3.79999pt on input line 111. + [1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map} + +] +[2 + +] (./Session-1.toc) [3 + +] [4 + +] [5 + +] [6 + +] +LaTeX Font Info: Try loading font information for T1+pcr on input line 180. + +(/usr/share/texmf-texlive/tex/latex/psnfss/t1pcr.fd +File: t1pcr.fd 2001/06/04 font definitions for T1/pcr. +) +LaTeX Font Info: Try loading font information for T1+ppl on input line 180. + +(/usr/share/texmf-texlive/tex/latex/psnfss/t1ppl.fd +File: t1ppl.fd 2001/06/04 font definitions for T1/ppl. +) +LaTeX Font Info: Try loading font information for U+eur on input line 180. + +(/usr/share/texmf-texlive/tex/latex/amsfonts/ueur.fd +File: ueur.fd 2002/01/19 v2.2g AMS font definitions +) +LaTeX Font Info: Try loading font information for OMS+zplm on input line 180 +. + +(/usr/share/texmf-texlive/tex/latex/psnfss/omszplm.fd +File: omszplm.fd 2002/09/08 Fontinst v1.914 font definitions for OMS/zplm. +) +LaTeX Font Info: Try loading font information for OMX+zplm on input line 180 +. + +(/usr/share/texmf-texlive/tex/latex/psnfss/omxzplm.fd +File: omxzplm.fd 2002/09/08 Fontinst v1.914 font definitions for OMX/zplm. +) +LaTeX Font Info: Font shape `U/msa/m/n' will be +(Font) scaled to size 15.0049pt on input line 180. +LaTeX Font Info: Font shape `U/msa/m/n' will be +(Font) scaled to size 10.42007pt on input line 180. +LaTeX Font Info: Font shape `U/msa/m/n' will be +(Font) scaled to size 8.33606pt on input line 180. +LaTeX Font Info: Font shape `U/msb/m/n' will be +(Font) scaled to size 15.0049pt on input line 180. +LaTeX Font Info: Font shape `U/msb/m/n' will be +(Font) scaled to size 10.42007pt on input line 180. +LaTeX Font Info: Font shape `U/msb/m/n' will be +(Font) scaled to size 8.33606pt on input line 180. +LaTeX Font Info: Try loading font information for OT1+zplm on input line 180 +. + +(/usr/share/texmf-texlive/tex/latex/psnfss/ot1zplm.fd +File: ot1zplm.fd 2002/09/08 Fontinst v1.914 font definitions for OT1/zplm. +) +LaTeX Font Info: Try loading font information for U+eus on input line 180. + +(/usr/share/texmf-texlive/tex/latex/amsfonts/ueus.fd +File: ueus.fd 2002/01/19 v2.2g AMS font definitions +) +LaTeX Font Info: Try loading font information for U+euex on input line 180. + +(/usr/share/texmf-texlive/tex/latex/amsfonts/ueuex.fd +File: ueuex.fd 2002/01/19 v2.2g AMS font definitions +) +LaTeX Font Info: Font shape `T1/phv/m/n' will be +(Font) scaled to size 9.49997pt on input line 180. +LaTeX Font Info: Font shape `T1/phv/m/it' in size <14.4> not available +(Font) Font shape `T1/phv/m/sl' tried instead on input line 180. +LaTeX Font Info: Font shape `T1/phv/m/sl' will be +(Font) scaled to size 13.67995pt on input line 180. +LaTeX Font Info: Font shape `T1/phv/m/it' in size <10> not available +(Font) Font shape `T1/phv/m/sl' tried instead on input line 180. +LaTeX Font Info: Font shape `T1/phv/m/sl' will be +(Font) scaled to size 9.49997pt on input line 180. +LaTeX Font Info: Font shape `T1/phv/m/it' in size <8> not available +(Font) Font shape `T1/phv/m/sl' tried instead on input line 180. +LaTeX Font Info: Font shape `T1/phv/m/sl' will be +(Font) scaled to size 7.59998pt on input line 180. + +Overfull \hbox (28.31342pt too wide) has occurred while \output is active +[] [] [] [] [] [] [] [] [] [] + [] + +[7 + +] +Overfull \hbox (28.31342pt too wide) has occurred while \output is active +[] [] [] [] [] [] [] [] [] [] + [] + +[8 + +] +LaTeX Font Info: Font shape `T1/phv/m/n' will be +(Font) scaled to size 11.39996pt on input line 209. +LaTeX Font Info: Font shape `U/msa/m/n' will be +(Font) scaled to size 12.50409pt on input line 209. +LaTeX Font Info: Font shape `U/msa/m/n' will be +(Font) scaled to size 9.37807pt on input line 209. +LaTeX Font Info: Font shape `U/msa/m/n' will be +(Font) scaled to size 7.29405pt on input line 209. +LaTeX Font Info: Font shape `U/msb/m/n' will be +(Font) scaled to size 12.50409pt on input line 209. +LaTeX Font Info: Font shape `U/msb/m/n' will be +(Font) scaled to size 9.37807pt on input line 209. +LaTeX Font Info: Font shape `U/msb/m/n' will be +(Font) scaled to size 7.29405pt on input line 209. +LaTeX Font Info: External font `euex7' loaded for size +(Font) <7> on input line 209. +LaTeX Font Info: Font shape `T1/phv/m/n' will be +(Font) scaled to size 8.54997pt on input line 209. +LaTeX Font Info: Font shape `T1/phv/m/n' will be +(Font) scaled to size 6.64998pt on input line 209. +LaTeX Font Info: Font shape `T1/phv/m/it' in size <12> not available +(Font) Font shape `T1/phv/m/sl' tried instead on input line 209. +LaTeX Font Info: Font shape `T1/phv/m/sl' will be +(Font) scaled to size 11.39996pt on input line 209. +LaTeX Font Info: Font shape `T1/phv/m/it' in size <9> not available +(Font) Font shape `T1/phv/m/sl' tried instead on input line 209. +LaTeX Font Info: Font shape `T1/phv/m/sl' will be +(Font) scaled to size 8.54997pt on input line 209. +LaTeX Font Info: Font shape `T1/phv/m/it' in size <7> not available +(Font) Font shape `T1/phv/m/sl' tried instead on input line 209. +LaTeX Font Info: Font shape `T1/phv/m/sl' will be +(Font) scaled to size 6.64998pt on input line 209. + +Overfull \hbox (28.31342pt too wide) has occurred while \output is active +[] [] [] [] [] [] [] [] [] [] + [] + +[9 + +] +Overfull \hbox (28.31342pt too wide) has occurred while \output is active +[] [] [] [] [] [] [] [] [] [] + [] + +[10 + +] +Overfull \hbox (28.31342pt too wide) has occurred while \output is active +[] [] [] [] [] [] [] [] [] [] + [] + +[11 + +] +Overfull \hbox (28.31342pt too wide) has occurred while \output is active +[] [] [] [] [] [] [] [] [] [] + [] + +[12 + +] (./Session-1.toc) [13 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +LaTeX Font Info: Font shape `T1/pcr/bx/n' in size <14.4> not available +(Font) Font shape `T1/pcr/b/n' tried instead on input line 2. +) [14 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [15 + +] +\openout3 = `Session-1.vrb'. + + +(./Session-1.vrb) [16 + +] [17 + +] [18 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [19 + +] (./Session-1.vrb) +[20 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +LaTeX Font Info: Font shape `T1/pcr/m/it' in size <14.4> not available +(Font) Font shape `T1/pcr/m/sl' tried instead on input line 12. +) [21 + +] (./Session-1.toc) [22 + +] [23 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) +Overfull \vbox (0.29024pt too high) detected at line 394 + [] + +[24 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [25 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [26 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (3.75285pt too wide) in paragraph at lines 5--6 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ +][][][][][][][][] + [] + + +Overfull \hbox (12.39293pt too wide) in paragraph at lines 10--11 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ +][][][][][][][][][][][][][] + [] + +) [27 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (38.31316pt too wide) in paragraph at lines 10--11 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ +][][][][][][][][][][][][] + [] + + +Overfull \hbox (124.71391pt too wide) in paragraph at lines 18--19 +[][][][][][][][][][][][][][][][][][] + [] + +) [28 + +] (./Session-1.vrb +Overfull \hbox (38.31316pt too wide) in paragraph at lines 10--11 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ +][][][][][][][][][][][][] + [] + + +Overfull \hbox (124.71391pt too wide) in paragraph at lines 18--19 +[][][][][][][][][][][][][][][][][][] + [] + +) [29 + +] [30 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [31 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (12.39293pt too wide) in paragraph at lines 6--7 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ +][][][][][][][][][][][][][][][][][][][][][][] + [] + +) [32 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [33 + +] [34 + +] (./Session-1.toc) [35 + +] [36 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [37 + +] [38 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (29.67308pt too wide) in paragraph at lines 3--4 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][] + [] + +) [39 + +] [40 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [41 + +] [42 + +] [43 + +] [44 + +] [45 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) +[46 + +] (./Session-1.vrb) [47 + +] (./Session-1.toc) [48 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [49 + +] +\openout3 = `Session-1.vrb'. + + +(./Session-1.vrb) [50 + +] (./Session-1.vrb) [51 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [52 + +] +\openout3 = `Session-1.vrb'. + + +(./Session-1.vrb) [53 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [54 + +] [55 + +] [56 + +] [57 + +] [58 + +] [59 + +] [60 + +] +[61 + +] (./Session-1.toc) [62 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [63 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [64 + +] +\openout3 = `Session-1.vrb'. + + +(./Session-1.vrb) [65 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [66 + +] (./Session-1.vrb) [67 + +] +\openout3 = `Session-1.vrb'. + + +(./Session-1.vrb +Overfull \hbox (3.75285pt too wide) in paragraph at lines 7--8 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][] + [] + +) [68 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (21.033pt too wide) in paragraph at lines 10--11 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][] + [] + +) [69 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (12.39293pt too wide) in paragraph at lines 3--4 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ +][][][][][][][][][][][][] + [] + +) [70 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (29.67308pt too wide) in paragraph at lines 9--10 +[][][][][][][][][][][][][][][][] + [] + +) [71 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [72 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [73 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (29.67308pt too wide) in paragraph at lines 6--7 +[][][][][][][][][][][][][][][][][][][][][][][][][][][] + [] + +) [74 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (12.39293pt too wide) in paragraph at lines 3--4 +[][][][][][][][][][][][][][][][][][][][][][][][][] + [] + +) [75 + +] [76 + +] [77 + +] [78 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (29.67308pt too wide) in paragraph at lines 10--11 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][] + [] + +) [79 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [80 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [81 + +] (./Session-1.toc) [82 + +] +\openout3 = `Session-1.vrb'. + + +(./Session-1.vrb) [83 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [84 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (29.67308pt too wide) in paragraph at lines 4--5 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][] + [] + + +Overfull \hbox (38.31316pt too wide) in paragraph at lines 5--6 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][] + [] + + +Overfull \hbox (29.67308pt too wide) in paragraph at lines 10--11 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][ +][][][][][][] + [] + +) [85 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) +LaTeX Font Info: Font shape `T1/pcr/bx/n' in size <20.74> not available +(Font) Font shape `T1/pcr/b/n' tried instead on input line 1098. + [86 + +] +Overfull \hbox (12.3901pt too wide) in paragraph at lines 1105--1105 +[]\T1/pcr/m/n/14.4 RGN;ID;NAME;MARK1;...;MARK5;TOTAL;PFW + [] + +[87 + +] [88 + +] (./Session-1.toc) [89 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb +Overfull \hbox (12.39293pt too wide) in paragraph at lines 4--5 +[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][] + [] + + +Overfull \hbox (12.39293pt too wide) in paragraph at lines 5--6 +[][][][][][][][][][][][][][][][][][][][][][][][][][] + [] + +) [90 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [91 + +] [92 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [93 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) +[94 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) +Overfull \vbox (1.35773pt too high) detected at line 1217 + [] + +[95 + +] +\openout3 = `Session-1.vrb'. + + (./Session-1.vrb) [96 + +] (./Session-1.toc) [97 + +] [98 + +] +\tf@nav=\write5 +\openout5 = `Session-1.nav'. + +\tf@toc=\write6 +\openout6 = `Session-1.toc'. + +\tf@snm=\write7 +\openout7 = `Session-1.snm'. + + (./Session-1.aux) ) +Here is how much of TeX's memory you used: + 14565 strings out of 94834 + 245982 string characters out of 1179181 + 313426 words of memory out of 1500000 + 17007 multiletter control sequences out of 10000+50000 + 67454 words of font info for 118 fonts, out of 1200000 for 2000 + 212 hyphenation exceptions out of 8191 + 43i,16n,65p,317b,1250s stack positions out of 5000i,500n,6000p,200000b,5000s +pdfTeX warning (dest): name{Outline0.3.7.88} has been refer +enced but does not exist, replaced by a fixed one + +pdfTeX warning (dest): name{Outline0.3.6.81} has been referenced but does not e +xist, replaced by a fixed one + +pdfTeX warning (dest): name{Outline0.3.5.61} has been referenced but does not e +xist, replaced by a fixed one + +pdfTeX warning (dest): name{Outline0.3.4.47} has been referenced but does not e +xist, replaced by a fixed one + +pdfTeX warning (dest): name{Outline0.3.3.34} has been referenced but does not e +xist, replaced by a fixed one + +pdfTeX warning (dest): name{Outline0.3.2.21} has been referenced but does not e +xist, replaced by a fixed one + +pdfTeX warning (dest): name{Outline0.3.1.12} has been referenced but does not e +xist, replaced by a fixed one + +{/usr/share/texmf-texlive/fonts/enc/dvips/base/8r.enc}</usr/share/texmf-texlive +/fonts/type1/bluesky/ams/euex10.pfb></usr/share/texmf-texlive/fonts/type1/blues +ky/ams/eufm10.pfb></usr/share/texmf-texlive/fonts/type1/urw/courier/ucrb8a.pfb> +</usr/share/texmf-texlive/fonts/type1/urw/courier/ucrr8a.pfb></usr/share/texmf- +texlive/fonts/type1/urw/courier/ucrro8a.pfb></usr/share/texmf-texlive/fonts/typ +e1/urw/helvetic/uhvr8a.pfb></usr/share/texmf-texlive/fonts/type1/urw/helvetic/u +hvro8a.pfb></usr/share/texmf-texlive/fonts/type1/urw/palatino/uplr8a.pfb> +Output written on Session-1.pdf (98 pages, 746718 bytes). +PDF statistics: + 3180 PDF objects out of 3580 (max. 8388607) + 215 named destinations out of 1000 (max. 131072) + 219 words of extra memory for PDF output out of 10000 (max. 10000000) + diff --git a/day1/Session-1.nav b/day1/Session-1.nav new file mode 100644 index 0000000..37f26e6 --- /dev/null +++ b/day1/Session-1.nav @@ -0,0 +1,211 @@ +\beamer@endinputifotherversion {3.07pt} +\headcommand {\slideentry {0}{0}{1}{1/1}{}{0}} +\headcommand {\beamer@framepages {1}{1}} +\headcommand {\slideentry {0}{0}{2}{2/2}{}{0}} +\headcommand {\beamer@framepages {2}{2}} +\headcommand {\slideentry {0}{0}{3}{3/3}{}{0}} +\headcommand {\beamer@framepages {3}{3}} +\headcommand {\sectionentry {1}{Agenda}{4}{Agenda}{0}} +\headcommand {\beamer@sectionpages {1}{3}} +\headcommand {\beamer@subsectionpages {1}{3}} +\headcommand {\slideentry {1}{0}{4}{4/4}{}{0}} +\headcommand {\beamer@framepages {4}{4}} +\headcommand {\sectionentry {2}{Agenda}{5}{Agenda}{0}} +\headcommand {\beamer@sectionpages {4}{4}} +\headcommand {\beamer@subsectionpages {4}{4}} +\headcommand {\slideentry {2}{0}{5}{5/5}{}{0}} +\headcommand {\beamer@framepages {5}{5}} +\headcommand {\slideentry {2}{0}{6}{6/6}{}{0}} +\headcommand {\beamer@framepages {6}{6}} +\headcommand {\sectionentry {3}{Overview}{7}{Overview}{0}} +\headcommand {\beamer@sectionpages {5}{6}} +\headcommand {\beamer@subsectionpages {5}{6}} +\headcommand {\slideentry {3}{0}{7}{7/7}{}{0}} +\headcommand {\beamer@framepages {7}{7}} +\headcommand {\slideentry {3}{0}{8}{8/8}{}{0}} +\headcommand {\beamer@framepages {8}{8}} +\headcommand {\slideentry {3}{0}{9}{9/9}{}{0}} +\headcommand {\beamer@framepages {9}{9}} +\headcommand {\slideentry {3}{0}{10}{10/10}{}{0}} +\headcommand {\beamer@framepages {10}{10}} +\headcommand {\slideentry {3}{0}{11}{11/11}{}{0}} +\headcommand {\beamer@framepages {11}{11}} +\headcommand {\slideentry {3}{0}{12}{12/12}{}{0}} +\headcommand {\beamer@framepages {12}{12}} +\headcommand {\sectionentry {4}{Python}{13}{Python}{0}} +\headcommand {\beamer@sectionpages {7}{12}} +\headcommand {\beamer@subsectionpages {7}{12}} +\headcommand {\beamer@subsectionentry {0}{4}{1}{13}{Getting Started}}\headcommand {\beamer@subsectionpages {13}{12}} +\headcommand {\slideentry {4}{1}{1}{13/13}{Getting Started}{0}} +\headcommand {\beamer@framepages {13}{13}} +\headcommand {\slideentry {4}{1}{2}{14/14}{Getting Started}{0}} +\headcommand {\beamer@framepages {14}{14}} +\headcommand {\slideentry {4}{1}{3}{15/15}{Getting Started}{0}} +\headcommand {\beamer@framepages {15}{15}} +\headcommand {\slideentry {4}{1}{4}{16/16}{Getting Started}{0}} +\headcommand {\beamer@framepages {16}{16}} +\headcommand {\slideentry {4}{1}{5}{17/17}{Getting Started}{0}} +\headcommand {\beamer@framepages {17}{17}} +\headcommand {\slideentry {4}{1}{6}{18/18}{Getting Started}{0}} +\headcommand {\beamer@framepages {18}{18}} +\headcommand {\slideentry {4}{1}{7}{19/20}{Getting Started}{0}} +\headcommand {\beamer@framepages {19}{20}} +\headcommand {\slideentry {4}{1}{8}{21/21}{Getting Started}{0}} +\headcommand {\beamer@framepages {21}{21}} +\headcommand {\beamer@subsectionentry {0}{4}{2}{22}{Data types}}\headcommand {\beamer@subsectionpages {13}{21}} +\headcommand {\slideentry {4}{2}{1}{22/22}{Data types}{0}} +\headcommand {\beamer@framepages {22}{22}} +\headcommand {\slideentry {4}{2}{2}{23/23}{Data types}{0}} +\headcommand {\beamer@framepages {23}{23}} +\headcommand {\slideentry {4}{2}{3}{24/24}{Data types}{0}} +\headcommand {\beamer@framepages {24}{24}} +\headcommand {\slideentry {4}{2}{4}{25/25}{Data types}{0}} +\headcommand {\beamer@framepages {25}{25}} +\headcommand {\slideentry {4}{2}{5}{26/26}{Data types}{0}} +\headcommand {\beamer@framepages {26}{26}} +\headcommand {\slideentry {4}{2}{6}{27/27}{Data types}{0}} +\headcommand {\beamer@framepages {27}{27}} +\headcommand {\slideentry {4}{2}{7}{28/29}{Data types}{0}} +\headcommand {\beamer@framepages {28}{29}} +\headcommand {\slideentry {4}{2}{8}{30/30}{Data types}{0}} +\headcommand {\beamer@framepages {30}{30}} +\headcommand {\slideentry {4}{2}{9}{31/31}{Data types}{0}} +\headcommand {\beamer@framepages {31}{31}} +\headcommand {\slideentry {4}{2}{10}{32/32}{Data types}{0}} +\headcommand {\beamer@framepages {32}{32}} +\headcommand {\slideentry {4}{2}{11}{33/33}{Data types}{0}} +\headcommand {\beamer@framepages {33}{33}} +\headcommand {\slideentry {4}{2}{12}{34/34}{Data types}{0}} +\headcommand {\beamer@framepages {34}{34}} +\headcommand {\beamer@subsectionentry {0}{4}{3}{35}{Control flow}}\headcommand {\beamer@subsectionpages {22}{34}} +\headcommand {\slideentry {4}{3}{1}{35/35}{Control flow}{0}} +\headcommand {\beamer@framepages {35}{35}} +\headcommand {\slideentry {4}{3}{2}{36/36}{Control flow}{0}} +\headcommand {\beamer@framepages {36}{36}} +\headcommand {\slideentry {4}{3}{3}{37/37}{Control flow}{0}} +\headcommand {\beamer@framepages {37}{37}} +\headcommand {\slideentry {4}{3}{4}{38/38}{Control flow}{0}} +\headcommand {\beamer@framepages {38}{38}} +\headcommand {\slideentry {4}{3}{5}{39/39}{Control flow}{0}} +\headcommand {\beamer@framepages {39}{39}} +\headcommand {\slideentry {4}{3}{6}{40/40}{Control flow}{0}} +\headcommand {\beamer@framepages {40}{40}} +\headcommand {\slideentry {4}{3}{7}{41/41}{Control flow}{0}} +\headcommand {\beamer@framepages {41}{41}} +\headcommand {\slideentry {4}{3}{8}{42/42}{Control flow}{0}} +\headcommand {\beamer@framepages {42}{42}} +\headcommand {\slideentry {4}{3}{9}{43/43}{Control flow}{0}} +\headcommand {\beamer@framepages {43}{43}} +\headcommand {\slideentry {4}{3}{10}{44/44}{Control flow}{0}} +\headcommand {\beamer@framepages {44}{44}} +\headcommand {\slideentry {4}{3}{11}{45/45}{Control flow}{0}} +\headcommand {\beamer@framepages {45}{45}} +\headcommand {\slideentry {4}{3}{12}{46/47}{Control flow}{0}} +\headcommand {\beamer@framepages {46}{47}} +\headcommand {\beamer@subsectionentry {0}{4}{4}{48}{Functions}}\headcommand {\beamer@subsectionpages {35}{47}} +\headcommand {\slideentry {4}{4}{1}{48/48}{Functions}{0}} +\headcommand {\beamer@framepages {48}{48}} +\headcommand {\slideentry {4}{4}{2}{49/49}{Functions}{0}} +\headcommand {\beamer@framepages {49}{49}} +\headcommand {\slideentry {4}{4}{3}{50/51}{Functions}{0}} +\headcommand {\beamer@framepages {50}{51}} +\headcommand {\slideentry {4}{4}{4}{52/52}{Functions}{0}} +\headcommand {\beamer@framepages {52}{52}} +\headcommand {\slideentry {4}{4}{5}{53/53}{Functions}{0}} +\headcommand {\beamer@framepages {53}{53}} +\headcommand {\slideentry {4}{4}{6}{54/54}{Functions}{0}} +\headcommand {\beamer@framepages {54}{54}} +\headcommand {\slideentry {4}{4}{7}{55/55}{Functions}{0}} +\headcommand {\beamer@framepages {55}{55}} +\headcommand {\slideentry {4}{4}{8}{56/56}{Functions}{0}} +\headcommand {\beamer@framepages {56}{56}} +\headcommand {\slideentry {4}{4}{9}{57/57}{Functions}{0}} +\headcommand {\beamer@framepages {57}{57}} +\headcommand {\slideentry {4}{4}{10}{58/58}{Functions}{0}} +\headcommand {\beamer@framepages {58}{58}} +\headcommand {\slideentry {4}{4}{11}{59/59}{Functions}{0}} +\headcommand {\beamer@framepages {59}{59}} +\headcommand {\slideentry {4}{4}{12}{60/60}{Functions}{0}} +\headcommand {\beamer@framepages {60}{60}} +\headcommand {\slideentry {4}{4}{13}{61/61}{Functions}{0}} +\headcommand {\beamer@framepages {61}{61}} +\headcommand {\beamer@subsectionentry {0}{4}{5}{62}{Lists}}\headcommand {\beamer@subsectionpages {48}{61}} +\headcommand {\slideentry {4}{5}{1}{62/62}{Lists}{0}} +\headcommand {\beamer@framepages {62}{62}} +\headcommand {\slideentry {4}{5}{2}{63/63}{Lists}{0}} +\headcommand {\beamer@framepages {63}{63}} +\headcommand {\slideentry {4}{5}{3}{64/64}{Lists}{0}} +\headcommand {\beamer@framepages {64}{64}} +\headcommand {\slideentry {4}{5}{4}{65/65}{Lists}{0}} +\headcommand {\beamer@framepages {65}{65}} +\headcommand {\slideentry {4}{5}{5}{66/67}{Lists}{0}} +\headcommand {\beamer@framepages {66}{67}} +\headcommand {\slideentry {4}{5}{6}{68/68}{Lists}{0}} +\headcommand {\beamer@framepages {68}{68}} +\headcommand {\slideentry {4}{5}{7}{69/69}{Lists}{0}} +\headcommand {\beamer@framepages {69}{69}} +\headcommand {\slideentry {4}{5}{8}{70/70}{Lists}{0}} +\headcommand {\beamer@framepages {70}{70}} +\headcommand {\slideentry {4}{5}{9}{71/71}{Lists}{0}} +\headcommand {\beamer@framepages {71}{71}} +\headcommand {\slideentry {4}{5}{10}{72/72}{Lists}{0}} +\headcommand {\beamer@framepages {72}{72}} +\headcommand {\slideentry {4}{5}{11}{73/73}{Lists}{0}} +\headcommand {\beamer@framepages {73}{73}} +\headcommand {\slideentry {4}{5}{12}{74/74}{Lists}{0}} +\headcommand {\beamer@framepages {74}{74}} +\headcommand {\slideentry {4}{5}{13}{75/75}{Lists}{0}} +\headcommand {\beamer@framepages {75}{75}} +\headcommand {\slideentry {4}{5}{14}{76/76}{Lists}{0}} +\headcommand {\beamer@framepages {76}{76}} +\headcommand {\slideentry {4}{5}{15}{77/77}{Lists}{0}} +\headcommand {\beamer@framepages {77}{77}} +\headcommand {\slideentry {4}{5}{16}{78/78}{Lists}{0}} +\headcommand {\beamer@framepages {78}{78}} +\headcommand {\slideentry {4}{5}{17}{79/79}{Lists}{0}} +\headcommand {\beamer@framepages {79}{79}} +\headcommand {\slideentry {4}{5}{18}{80/80}{Lists}{0}} +\headcommand {\beamer@framepages {80}{80}} +\headcommand {\slideentry {4}{5}{19}{81/81}{Lists}{0}} +\headcommand {\beamer@framepages {81}{81}} +\headcommand {\beamer@subsectionentry {0}{4}{6}{82}{IO}}\headcommand {\beamer@subsectionpages {62}{81}} +\headcommand {\slideentry {4}{6}{1}{82/82}{IO}{0}} +\headcommand {\beamer@framepages {82}{82}} +\headcommand {\slideentry {4}{6}{2}{83/83}{IO}{0}} +\headcommand {\beamer@framepages {83}{83}} +\headcommand {\slideentry {4}{6}{3}{84/84}{IO}{0}} +\headcommand {\beamer@framepages {84}{84}} +\headcommand {\slideentry {4}{6}{4}{85/85}{IO}{0}} +\headcommand {\beamer@framepages {85}{85}} +\headcommand {\slideentry {4}{6}{5}{86/86}{IO}{0}} +\headcommand {\beamer@framepages {86}{86}} +\headcommand {\slideentry {4}{6}{6}{87/87}{IO}{0}} +\headcommand {\beamer@framepages {87}{87}} +\headcommand {\slideentry {4}{6}{7}{88/88}{IO}{0}} +\headcommand {\beamer@framepages {88}{88}} +\headcommand {\beamer@subsectionentry {0}{4}{7}{89}{Modules}}\headcommand {\beamer@subsectionpages {82}{88}} +\headcommand {\slideentry {4}{7}{1}{89/89}{Modules}{0}} +\headcommand {\beamer@framepages {89}{89}} +\headcommand {\slideentry {4}{7}{2}{90/90}{Modules}{0}} +\headcommand {\beamer@framepages {90}{90}} +\headcommand {\slideentry {4}{7}{3}{91/91}{Modules}{0}} +\headcommand {\beamer@framepages {91}{91}} +\headcommand {\slideentry {4}{7}{4}{92/92}{Modules}{0}} +\headcommand {\beamer@framepages {92}{92}} +\headcommand {\slideentry {4}{7}{5}{93/93}{Modules}{0}} +\headcommand {\beamer@framepages {93}{93}} +\headcommand {\slideentry {4}{7}{6}{94/94}{Modules}{0}} +\headcommand {\beamer@framepages {94}{94}} +\headcommand {\slideentry {4}{7}{7}{95/95}{Modules}{0}} +\headcommand {\beamer@framepages {95}{95}} +\headcommand {\slideentry {4}{7}{8}{96/96}{Modules}{0}} +\headcommand {\beamer@framepages {96}{96}} +\headcommand {\slideentry {4}{7}{9}{97/97}{Modules}{0}} +\headcommand {\beamer@framepages {97}{97}} +\headcommand {\slideentry {4}{7}{10}{98/98}{Modules}{0}} +\headcommand {\beamer@framepages {98}{98}} +\headcommand {\beamer@partpages {1}{98}} +\headcommand {\beamer@subsectionpages {89}{98}} +\headcommand {\beamer@sectionpages {13}{98}} +\headcommand {\beamer@documentpages {98}} +\headcommand {\def \inserttotalframenumber {93}} diff --git a/day1/Session-1.out b/day1/Session-1.out new file mode 100644 index 0000000..75cb60f --- /dev/null +++ b/day1/Session-1.out @@ -0,0 +1,11 @@ +\BOOKMARK [2][]{Outline0.1}{Agenda}{} +\BOOKMARK [2][]{Outline0.2}{Agenda}{} +\BOOKMARK [2][]{Outline0.3}{Overview}{} +\BOOKMARK [2][]{Outline0.4}{Python}{} +\BOOKMARK [3][]{Outline0.4.1.13}{Getting Started}{Outline0.4} +\BOOKMARK [3][]{Outline0.4.2.22}{Data types}{Outline0.4} +\BOOKMARK [3][]{Outline0.4.3.35}{Control flow}{Outline0.4} +\BOOKMARK [3][]{Outline0.4.4.48}{Functions}{Outline0.4} +\BOOKMARK [3][]{Outline0.4.5.62}{Lists}{Outline0.4} +\BOOKMARK [3][]{Outline0.4.6.82}{IO}{Outline0.4} +\BOOKMARK [3][]{Outline0.4.7.89}{Modules}{Outline0.4} diff --git a/day1/Session-1.pdf b/day1/Session-1.pdf Binary files differnew file mode 100644 index 0000000..5a56a41 --- /dev/null +++ b/day1/Session-1.pdf diff --git a/day1/Session-1.snm b/day1/Session-1.snm new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/day1/Session-1.snm diff --git a/day1/Session-1.tex b/day1/Session-1.tex new file mode 100755 index 0000000..4052bff --- /dev/null +++ b/day1/Session-1.tex @@ -0,0 +1,2752 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Tutorial slides on Python. +% +% Author: Prabhu Ramachandran <prabhu at aero.iitb.ac.in> +% Copyright (c) 2005-2008, Prabhu Ramachandran +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} +%\documentclass[draft]{beamer} +%\documentclass[compress,handout]{beamer} +%\usepackage{pgfpages} +%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] + +% Modified from: generic-ornate-15min-45min.de.tex +\mode<presentation> +{ + \usetheme{Warsaw} + \useoutertheme{split} + \setbeamercovered{transparent} +} + +\usepackage[english]{babel} +\usepackage[latin1]{inputenc} +%\usepackage{times} +\usepackage[T1]{fontenc} + +% Taken from Fernando's slides. +\usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} +\usepackage[scaled=.95]{helvet} + +\definecolor{darkgreen}{rgb}{0,0.5,0} + +\usepackage{listings} +\lstset{language=Python, + basicstyle=\ttfamily, + commentstyle=\color{red}\itshape, + stringstyle=\color{darkgreen}, + showstringspaces=false, + keywordstyle=\color{blue}\bfseries} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Macros +\setbeamercolor{emphbar}{bg=blue!20, fg=black} +\newcommand{\emphbar}[1] +{\begin{beamercolorbox}[rounded=true]{emphbar} + {#1} + \end{beamercolorbox} +} +\newcounter{time} +\setcounter{time}{0} +\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} + +\newcommand{\typ}[1]{\texttt{#1}} + +\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } + +%%% This is from Fernando's setup. +% \usepackage{color} +% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} +% % Use and configure listings package for nicely formatted code +% \usepackage{listings} +% \lstset{ +% language=Python, +% basicstyle=\small\ttfamily, +% commentstyle=\ttfamily\color{blue}, +% stringstyle=\ttfamily\color{orange}, +% showstringspaces=false, +% breaklines=true, +% postbreak = \space\dots +% } + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Basic Python]{Python:\\A great programming toolkit} + +\author[Asokan \& Prabhu] {Asokan Pichai\\Prabhu Ramachandran} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {10, August 2009} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} +%\logo{\pgfuseimage{iitmlogo}} + + +%% Delete this, if you do not want the table of contents to pop up at +%% the beginning of each subsection: +\AtBeginSubsection[] +{ + \begin{frame}<beamer> + \frametitle{Outline} + \tableofcontents[currentsection,currentsubsection] + \end{frame} +} + + +% If you wish to uncover everything in a step-wise fashion, uncomment +% the following command: +%\beamerdefaultoverlayspecification{<+->} + +%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% DOCUMENT STARTS +\begin{document} + +\begin{frame} + \titlepage +\end{frame} +\begin{frame} + {Acknowledgements} + \begin{center} + This program is conducted by\\ + IIT, Bombay\\ + through CDEEP\\as part of the open source initiatives\\ + under the aegis of\\ + \alert{National Mission on Education through ICT,} \\ + Ministry of HRD. + \end{center} +\end{frame} + +\begin{frame} + \frametitle{Outline} + \tableofcontents + % You might wish to add the option [pausesections] +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TODO +% +% * Add slide on Python packages (modules) +% * Add slides on reference counting. + +\section{Agenda} +\begin{frame}{About the Workshop} + \begin{description} + \item[Day 1, Session 1] Sat 09:30--11:00 + \item[Day 1, Session 2] Sat 11:15--12:45 + \item[Day 1, Session 3] Sat 13:45--15:15 + \item[Day 1, Session 4] Sat 15:30--17:00 + \item[Day 2, Session 1] Sun 09:30--11:00 + \item[Day 2, Session 2] Sun 11:15--12:45 + \item[Day 2, Session 3] Sun 13:45--15:15 + \item[Day 2, Session 4] Sun 15:30--17:00 + \end{description} +\end{frame} + +\section{Agenda} +\begin{frame}{About the Workshop} + \begin{block}{Goal of the workshop} + At the end of this program, successful participants will be able to use python as their scripting and problem solving language. Aimed at Engg. students--focus on basic numerics and plotting-- but should serve a similar purpose for others. + \end{block} +\end{frame} + +\begin{frame}{Checklist} + Let us verify that all of us are having the same (similar) tools and environment + \begin{description} + \item[python] Type python at the command line. Do you see version 2.5 or later? + \item[IPython] Is IPython available? + \item[Editor] Which editor? scite, vim, emacs, \ldots + \end{description} +\end{frame} + +\section{Overview} +\begin{frame}{Session 1} + \begin{itemize} + \item Introduction and motivation + \item Using the interpreter(s) + \item Basic data types: int, float, string + \item Basic data structures: list + \item Basic console IO: \texttt{raw\_input(), print} + \item Basic control flow: \texttt{if, while} + \item Problem set 1 + \item Functions $\rightarrow$ Problem set 2 + \item lists, \texttt{for} $\rightarrow$ Problem set 3 + \item IO, Modules $\rightarrow$ Problem sets 4,5, \ldots + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Introduction} + \begin{itemize} + \item Creator and BDFL: Guido van Rossum + \item Conceived in December 1989 + \item ``Python'' as in Monty Python's Flying Circus + \item Current stable version of Python is 2.6.x + \item PSF license (like BSD: no strings attached) + \item Highly cross platform + \item Runs on the Nokia series 60! + \item \alert{Philosophy:} Simple and complete by design + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Resources} + \begin{itemize} + \item Part of many GNU/Linux distributions + \item Web: \url{http://www.python.org} + \item Doc: \url{http://www.python.org/doc} + \item Free Tutorials: + \begin{itemize} + \item Official Python tutorial: \url{http://docs.python.org/tut/tut.html} + \item Byte of Python: \url{http://www.byteofpython.info/} + \item Dive into Python: \url{http://diveintopython.org/} + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Why Python?} + \begin{itemize} + \item Designed to be readable and easy to use + \item High level, interpreted, modular, OO + \item Much faster development cycle + \item Powerful interactive environment + \item Rapid application development + \item Rich standard library and modules + \item Interfaces well with C++, C and FORTRAN + \item \alert{More than a math package $\Rightarrow$ some extra work compared to math packages} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Use cases} + \begin{itemize} + \item NASA: Space Shuttle Mission Design + \item AstraZeneca: Collaborative Drug Discovery + \item ForecastWatch.com: Helps Meteorologists + \item Industrial Light \& Magic: Runs on Python + \item Zope: Commercial grade Toolkit + \item Plone: Professional high feature CMS + \item RedHat: install scripts, sys-admin tools + \item Django: A great web application framework + \item Google: A strong python shop + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{To sum up, python is\ldots} + \begin{itemize} + \item dynamically typed, interpreted $\rightarrow$ rapid testing/prototyping + \item powerful, very high level + \item has full introspection + \item Did we mention powerful? + \end{itemize} + \begin{block}{But \ldots} + may be wanting in performance. specialised resources such as SWIG, \alert{Cython} are available + \end{block} + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 15m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\section{Python} + +\subsection{Getting Started} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> print 'Hello Python' +>>> print 3124 * 126789 +>>> 1786 % 12 +>>> 3124 * 126789 +>>> a = 3124 * 126789 +>>> big = 12345678901234567890 ** 3 +>>> verybig = big * big * big * big +>>> 12345**6, 12345**67, 12345**678 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> s = 'Hello ' +>>> p = 'World' +>>> s + p +>>> s * 12 +>>> s * s +>>> s + p * 12, (s + p)* 12 +>>> s * 12 + p * 12 +>>> 12 * s + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> 17/2 +>>> 17/2.0 +>>> 17.0/2 +>>> 17.0/8.5 +>>> int(17/2.0) +>>> float(17/2) +>>> str(17/2.0) +>>> round( 7.5 ) + \end{lstlisting} + \begin{block}{Mini exercise} + Round a float to the nearest integer, using \texttt{int()}? + \end{block} +\end{frame} + +\begin{frame}{Midi exercises} + \begin{center} + \begin{itemize} + \item What does this do? + \item \texttt{round(amount * 10) /10.0 } + \end{itemize} + \end{center} +\end{frame} + +\begin{frame}{More exercises?} + \begin{center} + \begin{block}{Round sums} + How to round a number to the nearest 5 paise?\\ + \begin{description} + \item[Remember] 17.23 $\rightarrow$ 17.25,\\ while 17.22 $\rightarrow$ 17.20\\ + \end{description} + How to round a number to the nearest 20 paise? + \end{block} + \end{center} +\end{frame} + +\begin{frame}[fragile] {A question of good style} + \begin{lstlisting} + amount = 12.68 + denom = 0.05 + nCoins = round(amount/denom) + rAmount = nCoins * denom + \end{lstlisting} + \pause + \begin{block}{Style Rule \#1} + Naming is 80\% of programming + \end{block} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item Case sensitive + \item Dynamically typed $\Rightarrow$ need not specify a type + \begin{lstlisting} +a = 1 +a = 1.1 +a = "Now I am a string!" + \end{lstlisting} + \item Comments: + \begin{lstlisting} +a = 1 # In-line comments +# Comment in a line to itself. +a = "# This is not a comment!" + \end{lstlisting} + \end{itemize} + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 30m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Data types} +\begin{frame} + \frametitle{Basic types} + \begin{itemize} + \item numbers: float, int, long, complex + \item strings + \item boolean + \end{itemize} + \begin{block}{Also to be discussed later} + tuples, lists, dictionaries, functions, objects\ldots + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Numbers} + \vspace*{-0.25in} + \begin{lstlisting} +>>> a = 1 # Int. +>>> l = 1000000L # Long +>>> e = 1.01325e5 # float +>>> f = 3.14159 # float +>>> c = 1+1j # Complex! +>>> print f*c/a +(3.14159+3.14159j) +>>> print c.real, c.imag +1.0 1.0 +>>> abs(c) +1.4142135623730951 +>>> abs( 8 - 9.5 ) +1.5 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Boolean} + \begin{lstlisting} +>>> t = True +>>> f = not t +False +>>> f or t +True +>>> f and t +False + \end{lstlisting} + \begin{block}{Try:} + NOT True\\ + not TRUE + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Relational and logical operators} + \begin{lstlisting} +>>> a, b, c = -1, 0, 1 +>>> a == b +False +>>> a <= b +True +>>> a + b != c +True +>>> a < b < c +True +>>> c >= a + b +True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Strings} + \begin{lstlisting} +s = 'this is a string' +s = 'This one has "quotes" inside!' +s = "I have 'single-quotes' inside!" +l = "A string spanning many lines\ +one more line\ +yet another" +t = """A triple quoted string does +not need to be escaped at the end and +"can have nested quotes" etc.""" + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More Strings} + \vspace*{-0.2in} + \begin{lstlisting} +>>> w = "hello" +>>> print w[0] + w[2] + w[-1] +hlo +>>> len(w) # guess what +5 +>>> s = u'Unicode strings!' +>>> # Raw strings (note the leading 'r') +... r_s = r'A string $\alpha \nu$' + \end{lstlisting} +\pause + \begin{lstlisting} +>>> w[0] = 'H' # Can't do that! +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: object does not support item assignment + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Let us switch to IPython} + Why? + \begin{block} + {Better help (and a lot more)} + Tab completion\\ + ?\\ + .?\\ + object.function? + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More on strings} + \begin{lstlisting} +In [1]: a = 'hello world' +In [2]: a.startswith('hell') +Out[2]: True +In [3]: a.endswith('ld') +Out[3]: True +In [4]: a.upper() +Out[4]: 'HELLO WORLD' +In [5]: a.upper().lower() +Out[5]: 'hello world' + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Still with strings} + \begin{lstlisting} +In [6]: a.split() +Out[6]: ['hello', 'world'] +In [7]: ''.join(['a', 'b', 'c']) +Out[7]: 'abc' +In [8] 'd' in ''.join( 'a', 'b', 'c') +Out[8]: False + \end{lstlisting} + \begin{block}{Try:} + \texttt{a.split( 'o' )}\\ + \texttt{'x'.join( a.split( 'o' ) )} + \end{block} +\end{frame} + +\begin{frame}[fragile]{Surprise! strings!!} + \begin{lstlisting} +In [11]: x, y = 1, 1.2 +In [12]: 'x is %s, y is %s' %(x, y) +Out[12]: 'x is 1, y is 1.234' + \end{lstlisting} + \begin{block}{Try:} + \texttt{'x is \%d, y is \%f' \%(x, y) }\\ + \texttt{'x is \%3d, y is \%4.2f' \%(x, y) } + \end{block} + \small +\url{docs.python.org/lib/typesseq-strings.html}\\ +\end{frame} + +\begin{frame} + {Interlude} + \begin{block} + {A classic problem} + How to interchange values of two variables? Please note that the type of either variable is unknown and it is not necessary that both be of the same type even! + \end{block} + \inctime{30} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 25 m+ Interlude break 5 mins, running 60m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Control flow} +\begin{frame} + \frametitle{Control flow constructs} + \begin{itemize} + \item \kwrd{if/elif/else}: branching + \item \kwrd{while}: looping + \item \kwrd{for}: iterating + \item \kwrd{break, continue}: modify loop + \item \kwrd{pass}: syntactic filler + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic conditional flow} + \begin{lstlisting} +In [21]: a = 7 +In [22]: b = 8 +In [23]: if a > b: + ....: print 'Hello' + ....: else: + ....: print 'World' + ....: + ....: +World + \end{lstlisting} + Let us switch to creating a file +\end{frame} + +\begin{frame} + {Creating python files} + \begin{itemize} + \item aka scripts + \item use your editor + \item Note that white space is the way to specify blocks! + \item extension \typ{.py} + \item run with \texttt{python hello.py} at the command line + \item in IPython\ldots + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{If...elif...else} example} +\begin{lstlisting} +x = int(raw_input("Enter an integer:")) +if x < 0: + print 'Be positive!' +elif x == 0: + print 'Zero' +elif x == 1: + print 'Single' +else: + print 'More' +\end{lstlisting} +\end{frame} + +\begin{frame}{Simple IO} + \begin{block} + {Console Input} + \texttt{raw\_input(}) waits for user input.\\Prompt string is optional.\\ + All keystrokes are Strings!\\\texttt{int()} converts string to int. + \end{block} + \begin{block} + {Console output} + \texttt{print} is straight forward. Major point to remember is the distinction between \texttt{print x} and \texttt{print x,} + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic looping} + \begin{lstlisting} +# Fibonacci series: +# the sum of two elements +# defines the next +a, b = 0, 1 +while b < 10: + print b, + a, b = b, a + b + +\end{lstlisting} +\typ{1 1 2 3 5 8}\\ +\alert{Recall it is easy to write infinite loops with \kwrd{while}} + \inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 80m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + \frametitle{Problem set 1} + \begin{itemize} + \item All the problems can be\\ + solved using \kwrd{if} and \kwrd{while} + \end{itemize} +\end{frame} + +\begin{frame}{Problem 1.1} + Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ +These are called $Armstrong$ numbers. +\end{frame} + +\begin{frame}{Problem 1.2 - Collatz sequence} +\begin{enumerate} + \item Start with an arbitrary (positive) integer. + \item If the number is even, divide by 2; if the number is odd multiply by 3 and add 1. + \item Repeat the procedure with the new number. + \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. +\end{enumerate} + Write a program that accepts the starting value and prints out the Collatz sequence. + +\end{frame} + +\begin{frame}{Problem 1.3 - Kaprekar's constant} + \begin{enumerate} + \item Take a four digit number--with at least two digits different. + \item Arrange the digits in ascending and descending order, giving A and D respectively. + \item Leave leading zeros in A! + \item Subtract A from D. + \item With the result, repeat from step 2. + \end{enumerate} + Write a program to accept a 4-digit number and display the progression to Kaprekar's constant. +\end{frame} + +\begin{frame}[fragile]{Problem 1.4} + Write a program that prints the following pyramid on the screen. + \begin{lstlisting} +1 +2 2 +3 3 3 +4 4 4 4 + \end{lstlisting} +The number of lines must be obtained from the user as input.\\ +\pause +When can your code fail? +\only<2->{\inctime{25}} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 25 m, running 105m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Functions} +\begin{frame}[fragile] +\frametitle{Functions: examples} + \begin{lstlisting} +def signum( r ): + """returns 0 if r is zero + -1 if r is negative + +1 if r is positive""" + if r < 0: + return -1 + elif r > 0: + return 1 + else: + return 0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: examples} + \begin{lstlisting} +def pad( n, size ): + """pads integer n with spaces + into a string of length size + """ + SPACE = ' ' + s = str( n ) + padSize = size - len( s ) + return padSize * SPACE + s + \end{lstlisting} +\pause +What about \%3d? +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} + \begin{lstlisting} +def what( n ): + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} +\begin{lstlisting} +def what( n ): + i = 1 + while i * i < n: + i += 1 + return i * i == n, i + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} + \begin{lstlisting} +def what( n, x ): + z = 1.0 + if n < 0: + x = 1.0 / x + n = -n + while n > 0: + if n % 2 == 1: + z *= x + n /= 2 + x *= x + return z + \end{lstlisting} +\end{frame} + +\begin{frame} + {Before writing a function} + \begin{itemize} + \item Builtin functions for various and sundry + \item \typ{abs, any, all, len, max, min} + \item \typ{pow, range, sum, type} + \item Refer here: + \url{http://docs.python.org/library/functions.html} + \end{itemize} + \inctime{15} +\end{frame} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 120m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame}{Problem set 2} + The focus is on writing functions and calling them. +\end{frame} + +\begin{frame}{Problem 2.1} + Write a function to return the gcd of two numbers. +\end{frame} + +\begin{frame}{Problem 2.2} +A pythagorean triad $(a,b,c)$ has the property $a^2 + b^2 = c^2$.\\By primitive we mean triads that do not `depend' on others. For example, (4,3,5) is a variant of (3,4,5) and hence is not primitive. And (10,24,26) is easily derived from (5,12,13) and should not be displayed by our program. \\ +Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100 +\end{frame} + +\begin{frame}{Problem 2.3} + Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\\For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square). +\end{frame} + +\begin{frame}{Problem 2.4} + The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. For example, the aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.\\ + Write a function that returns the aliquot number of a given number. +\end{frame} + +\begin{frame}{Problem 2.5} + A pair of numbers (a, b) is said to be \alert{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ + Example: \texttt{220, 284}\\ + Write a program that prints all five digit amicable pairs. + \inctime{30} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 30 m, running 150m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Lists} + +\begin{frame}[fragile] + \frametitle{List creation and indexing} +\begin{lstlisting} +>>> a = [] # An empty list. +>>> a = [1, 2, 3, 4] # More useful. +>>> len(a) +4 +>>> a[0] + a[1] + a[2] + a[-1] +10 +\end{lstlisting} + \begin{itemize} + \item Indices start with ? + \item Negative indices indicate ? + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: slices} + \begin{itemize} + \item Slicing is a basic operation + \item \typ{list[initial:final:step]} + \item The step is optional + \end{itemize} +\begin{lstlisting} +>>> a[1:3] # A slice. +[2, 3] +>>> a[1:-1] +[2, 3, 4] +>>> a[1:] == a[1:-1] +False +\end{lstlisting} +Explain last result +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: more slices} +\begin{lstlisting} +>>> a[0:-1:2] # Notice the step! +[1, 3] +>>> a[::2] +[1, 3] +>>> a[-1::-1] +\end{lstlisting} +What do you think the last one will do? + \emphbar{Note: Strings also use same indexing and slicing.} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: examples} +\begin{lstlisting} +>>> a = [1, 2, 3, 4] +>>> a[:2] +[1, 3] +>>> a[0:-1:2] +[1, 3] +\end{lstlisting} +\pause +\alert{Lists are mutable (unlike strings)} +\begin{lstlisting} +>>> a[1] = 20 +>>> a +[1, 20, 3, 4] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists are mutable and heterogenous} +\begin{lstlisting} +>>> a = ['spam', 'eggs', 100, 1234] +>>> a[2] = a[2] + 23 +>>> a +['spam', 'eggs', 123, 1234] +>>> a[0:2] = [1, 12] # Replace items +>>> a +[1, 12, 123, 1234] +>>> a[0:2] = [] # Remove items +>>> a.append( 12345 ) +>>> a +[123, 1234, 12345] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List methods} +\begin{lstlisting} +>>> a = ['spam', 'eggs', 1, 12] +>>> a.reverse() # in situ +>>> a +[12, 1, 'eggs', 'spam'] +>>> a.append(['x', 1]) +>>> a +[12, 1, 'eggs', 'spam', ['x', 1]] +>>> a.extend([1,2]) # Extend the list. +>>> a.remove( 'spam' ) +>>> a +[12, 1, 'eggs', ['x', 1], 1, 2] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List containership} + \begin{lstlisting} +>>> a = ['cat', 'dog', 'rat', 'croc'] +>>> 'dog' in a +True +>>> 'snake' in a +False +>>> 'snake' not in a +True +>>> 'ell' in 'hello world' +True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Tuples: immutable} +\begin{lstlisting} +>>> t = (0, 1, 2) +>>> print t[0], t[1], t[2], t[-1] +0 1 2 2 +>>> t[0] = 1 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: object does not support item + assignment +\end{lstlisting} +\begin{itemize} + \item Multiple return values are actually a tuple. + \item Exchange is tuple (un)packing +\end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{range()} function} + \begin{lstlisting} +>>> range(7) +[0, 1, 2, 3, 4, 5, 6] +>>> range( 3, 9) +[3, 4, 5, 6, 7, 8] +>>> range( 4, 17, 3) +[4, 7, 10, 13, 16] +>>> range( 5, 1, -1) +[5, 4, 3, 2] +>>> range( 8, 12, -1) +[] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for\ldots range(\ldots)} idiom} + \begin{lstlisting} +In [83]: for i in range(5): + ....: print i, i * i + ....: + ....: +0 0 +1 1 +2 4 +3 9 +4 16 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for}: the list companion} + + \begin{lstlisting} +In [84]: a = ['a', 'b', 'c'] +In [85]: for x in a: + ....: print x, chr( ord(x) + 10 ) + ....: +a k +b l +c m + \end{lstlisting} + Iterating over the list and not the index + reference\\ + what if you want the index? +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for}: the list companion} + \begin{lstlisting} +In [89]: for p, ch in enumerate( a ): + ....: print p, ch + ....: + ....: +0 a +1 b +2 c + \end{lstlisting} +Try: \typ{print enumerate(a)} +\inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 170m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + {Problem set 3} + As you can guess, idea is to use \kwrd{for}! +\end{frame} + +\begin{frame}{Problem 3.1} + Which of the earlier problems is simpler when we use \kwrd{for} instead of \kwrd{while}? +\end{frame} + +\begin{frame}{Problem 3.2} + Given an empty chessboard and one Bishop placed in any square, say (r, c), generate the list of all squares the Bishop could move to. +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.3} + + Given two real numbers \typ{a, b}, and an integer \typ{N}, write a + function named \typ{linspace( a, b, N)} that returns an ordered list + of \typ{N} points starting with \typ{a} and ending in \typ{b} and + equally spaced.\\ + + For example, \typ{linspace(0, 5, 11)}, should return, \\ +\begin{lstlisting} +[ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, + 3.0 , 3.5, 4.0 , 4.5, 5.0 ] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.4a (optional)} + +Use the \typ{linspace} function and generate a list of N tuples of the form\\ +\typ{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions,\begin{itemize} + \item \typ{f(x) = sin(x)} + \item \typ{f(x) = sin(x) + sin(10*x)}. +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.4b (optional)} + + Using the tuples generated earlier, determine the intervals where the roots of the functions lie. + + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 185m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{IO} + +\begin{frame}[fragile] + \frametitle{Simple tokenizing and parsing} + \begin{lstlisting} +s = """The quick brown fox jumped + over the lazy dog""" +for word in s.split(): + print word.capitalize() + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 4.1} + Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \\ + \begin{lstlisting} + [1,3,4,5,6,7,12,15,18,19,20,21] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File handling} +\begin{lstlisting} +>>> f = open('/path/to/file_name') +>>> data = f.read() # Read entire file. +>>> line = f.readline() # Read one line. +>>> f.close() # close the file. +\end{lstlisting} +Writing files +\begin{lstlisting} +>>> f = open('/path/to/file_name', 'w') +>>> f.write('hello world\n') +>>> f.close() +\end{lstlisting} +\begin{itemize} + \item Everything read or written is a string +\end{itemize} +\emphbar{Try \typ{file?} for more help} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File and \kwrd{for}} +\begin{lstlisting} +>>> f = open('/path/to/file_name') +>>> for line in f: +... print line +... +\end{lstlisting} +\end{frame} + +\begin{frame}{Problem 4.2} + The given file has lakhs of records in the form:\\ + \typ{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}\\ + Some entries may be empty. Read the data from this file and print the + name of the student with the maximum total marks. +\end{frame} + +\begin{frame}{Problem 4.3} + For the same data file compute the average marks in different + subjects, the student with the maximum mark in each subject and also + the standard deviation of the marks. Do this efficiently. + + \inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 205m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Modules} + +\begin{frame}[fragile] + {Modules} +\begin{lstlisting} +>>> sqrt(2) +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +NameError: name 'sqrt' is not defined +>>> import math +>>> math.sqrt(2) +1.4142135623730951 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {Modules} + \begin{itemize} + \item The \kwrd{import} keyword ``loads'' a module + \item One can also use: + \begin{lstlisting} +>>> from math import sqrt +>>> from math import * + \end{lstlisting} + \item What is the difference? + \item \alert{Use the later only in interactive mode} + \end{itemize} + \emphbar{Package hierarchies} + \begin{lstlisting} +>>> from os.path import exists + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Modules: Standard library} + \begin{itemize} + \item Very powerful, ``Batteries included'' + \item Some standard modules: + \begin{itemize} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib2}, \typ{smtplib} + \item System, Command line arguments: \typ{sys} + \item Operating system interface: \typ{os} + \item Regular expressions: \typ{re} + \item Compression: \typ{gzip}, \typ{zipfile}, and \typ{tarfile} + \item And a whole lot more! + \end{itemize} + \item Check out the Python Library reference: + \url{http://docs.python.org/library/} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + {Modules of special interest} + \begin{description}[matplotlibfor2d] + + \item[\typ{numpy}] Efficient, powerful numeric arrays + + \item[\typ{matplotlib}] Easy, interactive, 2D plotting + + \item[\typ{scipy}] statistics, optimization, integration, linear + algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + + \item[Mayavi] Easy, interactive, 3D plotting + + \end{description} +\end{frame} + +\begin{frame}[fragile] + {Creating your own modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \typ{.py} extension + \item This file becomes a module! + \item Accessible when in the current directory + \item Use \typ{cd} in IPython to change directory + + \item Naming your module + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- arith.py --- +def gcd(a, b): + if a%b == 0: return b + return gcd(b, a%b) +def lcm(a, b): + return a*b/gcd(a, b) +# ------------------ +>>> import arith +>>> arith.gcd(26, 65) +13 +>>> arith.lcm(26, 65) +130 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 5.1} + + Put all the functions you have written so far as part of the problems + into one module called \typ{iitb.py} and use this module from IPython. + +\inctime{20} +\end{frame} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 225m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + \frametitle{Did we meet the goal?} + \tableofcontents + % You might wish to add the option [pausesections] + \end{frame} + + \begin{frame} + {Tomorrow} + \begin{itemize} + \item Plotting: 2D, 3D + \item NumPy, SciPy + \item Dictionary, Set + \item Debugging + \item Testing + \item \ldots + \end{itemize} + 11:30--13:00 Discussion of answers to problems OPTIONAL + \end{frame} +\end{document} + + +\begin{frame}[fragile] + \frametitle{More on functions} + \begin{itemize} + \item Support default and keyword arguments + \item Scope of variables in the function is local + \item Mutable items are \alert{passed by reference} + \item First line after definition may be a documentation string + (\alert{recommended!}) + \item Function definition and execution defines a name bound to the + function + \item You \emph{can} assign a variable to a function! + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Functions: default arguments} + \begin{lstlisting} +def ask_ok(prompt, retries=4, complaint='Yes or no!'): + while True: + ok = raw_input(prompt) + if ok in ('y', 'ye', 'yes'): + return True + if ok in ('n', 'no', 'nop', 'nope'): + return False + retries = retries - 1 + if retries < 0: + raise IOError, 'bad user' + print complaint + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: keyword arguments} + \begin{lstlisting} +def parrot(voltage, state='a stiff', + action='voom', type='Norwegian Blue'): + print "-- This parrot wouldn't", action, + print "if you put", voltage, "Volts through it." + print "-- Lovely plumage, the", type + print "-- It's", state, "!" + +parrot(1000) +parrot(action = 'VOOOOOM', voltage = 1000000) +parrot('a thousand', state = 'pushing up the daisies') +parrot('a million', 'bereft of life', 'jump') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: arbitrary argument lists} + \begin{itemize} + \item Arbitrary number of arguments using \verb+*args+ or + \verb+*whatever+ + \item Keyword arguments using \verb+**kw+ + \item Given a tuple/dict how do you call a function? + \begin{itemize} + \item Using argument unpacking + \item For positional arguments: \verb+foo(*[5, 10])+ + \item For keyword args: \verb+foo(**{'a':5, 'b':10})+ + \end{itemize} + \end{itemize} +\begin{lstlisting} +def foo(a=10, b=100): + print a, b +def func(*args, **keyword): + print args, keyword +# Unpacking: +args = [5, 10] +foo(*args) +kw = {'a':5, 'b':10} +foo(**kw) +\end{lstlisting} +\end{frame} + +\subsection{Modules, exceptions, classes} + +\begin{frame} + \frametitle{Modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \typ{.py} extension + \item This file becomes a module! + \item Modules are searched in the following: + \begin{itemize} + \item Current directory + \item Standard: \typ{/usr/lib/python2.3/site-packages/} etc. + \item Directories specified in PYTHONPATH + \item \typ{sys.path}: current path settings (from the \typ{sys} + module) + \end{itemize} + \item The \typ{import} keyword ``loads'' a module + \item One can also use: + \mbox{\typ{from module import name1, name2, name2}}\\ + where \typ{name1} etc. are names in the module, ``module'' + \item \typ{from module import *} \ --- imports everything from module, + \alert{use only in interactive mode} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- foo.py --- +some_var = 1 +def fib(n): # write Fibonacci series up to n + """Print a Fibonacci series up to n.""" + a, b = 0, 1 + while b < n: + print b, + a, b = b, a+b +# EOF + +>>> import foo +>>> foo.fib(10) +1 1 2 3 5 8 +>>> foo.some_var +1 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Namespaces} + \begin{itemize} + \item A mapping from names to objects + \item Modules introduce a namespace + \item So do classes + \item The running script's namespace is \verb+__main__+ + \item A modules namespace is identified by its name + \item The standard functions (like \typ{len}) are in the + \verb+__builtin__+ namespace + \item Namespaces help organize different names and their bindings to + different objects + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Exceptions} + \begin{itemize} + \item Python's way of notifying you of errors + \item Several standard exceptions: \typ{SyntaxError}, \typ{IOError} + etc. + \item Users can also \typ{raise} errors + \item Users can create their own exceptions + \item Exceptions can be ``caught'' via \typ{try/except} blocks + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exception: examples} +\begin{lstlisting} +>>> 10 * (1/0) +Traceback (most recent call last): + File "<stdin>", line 1, in ? +ZeroDivisionError: integer division or modulo by zero +>>> 4 + spam*3 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +NameError: name 'spam' is not defined +>>> '2' + 2 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: cannot concatenate 'str' and 'int' objects +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exception: examples} +\begin{lstlisting} +>>> while True: +... try: +... x = int(raw_input("Enter a number: ")) +... break +... except ValueError: +... print "Invalid number, try again..." +... +>>> # To raise exceptions +... raise ValueError, "your error message" +Traceback (most recent call last): + File "<stdin>", line 2, in ? +ValueError: your error message +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: the big picture} + \begin{itemize} + \item Lets you create new data types + \item Class is a template for an object belonging to that class + \item Note: in Python a class is also an object + \item Instantiating a class creates an instance (an object) + \item An instance encapsulates the state (data) and behavior + (methods) + \item Allows you to define an inheritance hierarchy + \begin{itemize} + \item ``A Honda car \alert{is a} car.'' + \item ``A car \alert{is an} automobile.'' + \item ``A Python \alert{is a} reptile.'' + \end{itemize} + \item Programmers need to think OO + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: what's the big deal?} + \begin{itemize} + \item Lets you create objects that mimic a real problem being + simulated + \item Makes problem solving more natural and elegant + \item Easier to create code + \item Allows for code-reuse + \item Polymorphism + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Class definition and instantiation} + \begin{itemize} + \item Class definitions when executed create class objects + \item Instantiating the class object creates an instance of the + class + \end{itemize} +\footnotesize +\begin{lstlisting} +class Foo(object): + pass +# class object created. +# Create an instance of Foo. +f = Foo() +# Can assign an attribute to the instance +f.a = 100 +print f.a +100 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes \ldots} + \begin{itemize} + \item All attributes are accessed via the \typ{object.attribute} + syntax + \item Both class and instance attributes are supported + \item \emph{Methods} represent the behavior of an object: crudely + think of them as functions ``belonging'' to the object + \item All methods in Python are ``virtual'' + \item Inheritance through subclassing + \item Multiple inheritance is supported + \item No special public and private attributes: only good + conventions + \begin{itemize} + \item \verb+object.public()+: public + \item \verb+object._private()+ \& \verb+object.__priv()+: + non-public + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: examples} +\begin{lstlisting} +class MyClass(object): + """Example class (this is the class docstring).""" + i = 12345 # A class attribute + def f(self): + """This is the method docstring""" + return 'hello world' + +>>> a = MyClass() # creates an instance +>>> a.f() +'hello world' +>>> # a.f() is equivalent to MyClass.f(a) +... # This also explains why f has a 'self' argument. +... MyClass.f(a) +'hello world' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes (continued)} + \begin{itemize} + \item \typ{self} is \alert{conventionally} the first argument for a + method + \item In previous example, \typ{a.f} is a method object + \item When \typ{a.f} is called, it is passed the instance \typ{a} as + the first argument + \item If a method called \verb+__init__+ exists, it is called when + the object is created + \item If a method called \verb+__del__+ exists, it is called before + the object is garbage collected + \item Instance attributes are set by simply ``setting'' them in + \typ{self} + \item Other special methods (by convention) like \verb+__add__+ let + you define numeric types: + {\footnotesize \url{http://docs.python.org/ref/specialnames.html} + \\ \url{http://docs.python.org/ref/numeric-types.html} + } + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: examples} +\begin{lstlisting} +class Bag(MyClass): # Shows how to derive classes + def __init__(self): # called on object creation. + self.data = [] # an instance attribute + def add(self, x): + self.data.append(x) + def addtwice(self, x): + self.add(x) + self.add(x) +>>> a = Bag() +>>> a.f() # Inherited method +'hello world' +>>> a.add(1); a.addtwice(2) +>>> a.data +[1, 2, 2] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Derived classes} + \begin{itemize} + \item Call the parent's \verb+__init__+ if needed + \item If you don't need a new constructor, no need to define it in subclass + \item Can also use the \verb+super+ built-in function + \end{itemize} +\begin{lstlisting} +class AnotherBag(Bag): + def __init__(self): + # Must call parent's __init__ explicitly + Bag.__init__(self) + # Alternatively use this: + super(AnotherBag, self).__init__() + # Now setup any more data. + self.more_data = [] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: polymorphism} +\begin{lstlisting} +class Drawable(object): + def draw(self): + # Just a specification. + pass +\end{lstlisting} +\mode<presentation>{\pause} +\begin{lstlisting} +class Square(Drawable): + def draw(self): + # draw a square. +class Circle(Drawable): + def draw(self): + # draw a circle. +\end{lstlisting} +\mode<presentation>{\pause} +\begin{lstlisting} +class Artist(Drawable): + def draw(self): + for obj in self.drawables: + obj.draw() +\end{lstlisting} +\end{frame} + +\subsection{Miscellaneous} + +\begin{frame}[fragile] + \frametitle{Stand-alone scripts} +Consider a file \typ{f.py}: +\begin{lstlisting} +#!/usr/bin/env python +"""Module level documentation.""" +# First line tells the shell that it should use Python +# to interpret the code in the file. +def f(): + print "f" + +# Check if we are running standalone or as module. +# When imported, __name__ will not be '__main__' +if __name__ == '__main__': + # This is not executed when f.py is imported. + f() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List comprehensions} +\begin{lstlisting} +>>> veg = ['tomato', 'cabbage', 'carrot', 'potato'] +>>> [x.upper() for x in veg] +['TOMATO', 'CABBAGE', 'CARROT', 'POTATO'] +>>> vec = range(0, 8) +>>> even = [x for x in vec if x%2 == 0] +>>> even +[0, 2, 4, 6] +>>> [x*x for x in even] +[0, 4, 16, 36] +>>> odd = [x for x in vec if x%2 == 1] +>>> odd +[1, 3, 5, 7] +>>> [x*y for x in even for y in odd] +[0, 0, 0, 0, 2, 6, 10, 14, 4, 12, 20, 28, 6, 18,30,42] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features} + \begin{itemize} + \item Input and output caching: + \begin{itemize} + \item \verb+In+: a list of all entered input + \item \verb+Out+: a dict of all output + \item \verb+_+, \verb+__+, \verb+__+ are the last three results as + is \verb+_N+ + \item \verb+%hist [-n]+ macro shows previous history, \verb+-n+ + suppresses line number information + \end{itemize} + \item Log the session using \verb+%logstart+, \verb+%logon+ and + \verb+%logoff+ + \item \verb+%run [options] file[.py]+ -- running Python code + \begin{itemize} + \item \verb+%run -d [-b<N>]+: debug script with pdb + \verb+N+ is the line number to break at (defaults to 1) + \item \verb+%run -t+: time the script + \item \verb+%run -p+: Profile the script + \end{itemize} + \item \verb+%prun+ runs a statement/expression under the profiler + \item \verb+%macro [options] macro_name n1-n2 n3-n4 n6+ save specified + lines to a macro with name \verb+macro_name+ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features \ldots} + \begin{itemize} + \item \verb+%edit [options] [args]+: edit lines of code or file + specified in editor (configure editor via \verb+$EDITOR+) + \item \verb+%cd+ changes directory, see also \verb+%pushd, %popd, %dhist+ + \item Shell access + \begin{itemize} + \item \verb+!command+ runs a shell command and returns its output + \item \verb+files = %sx ls+ or \verb+files = !ls+ sets + \verb+files+ to all result of the \verb+ls+ command + \item \verb+%sx+ is quiet + \item \verb+!ls $files+ passes the \verb+files+ variable to the + shell command + \item \verb+%alias alias_name cmd+ creates an alias for a system + command + \end{itemize} + \item \verb+%colors+ lets you change the color scheme to + \verb+NoColor, Linux, LightBG+ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features \ldots} + \begin{itemize} + \item Use \verb+;+ at the end of a statement to suppress printing + output + \item \verb+%bookmark+: store a bookmarked location, for use with \verb+%cd+ + \item \verb+%who, %whos+: print information on variables + \item \verb+%save [options] filename n1-n2 n3-n4+: save lines to a + file + \item \verb+%time statement+: Time execution of a Python statement or + expression + \item \verb+%timeit [-n<N> -r<R> [-t|-c]] statement+: time execution + using Python's timeit module + \item Can define and use profiles to setup IPython differently: + \verb+math, scipy, numeric, pysh+ etc. + \item \verb+%magic+: \alert{Show help on all magics} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File handling} +\begin{lstlisting} +>>> # Reading files: +... f = open('/path/to/file_name') +>>> data = f.read() # Read entire file. +>>> line = f.readline() # Read one line. +>>> # Read entire file appending each line into a list +... lines = f.readlines() +>>> f.close() # close the file. +>>> # Writing files: +... f = open('/path/to/file_name', 'w') +>>> f.write('hello world\n') +\end{lstlisting} + \begin{itemize} + \item \typ{tell()}: returns int of current position + \item \typ{seek(pos)}: moves current position to specified byte + \item Call \typ{close()} when done using a file + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Math} + \begin{itemize} + \item \typ{math} module provides basic math routines for + floats + \item \typ{cmath} module provides math routies for complex + numbers + \item \typ{random}: provides pseudo-random number generators + for various distributions + \item These are always available and part of the standard library + \item More serious math is provided by the NumPy/SciPy modules -- + these are not standard and need to be installed separately + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Timing and profiling} + \begin{itemize} + \item Timing code: use the \typ{time} module + \item Read up on \typ{time.time()} and \typ{time.clock()} + \item \typ{timeit}: is a better way of doing timing + \item IPython has handy \typ{time} and \typ{timeit} macros (type + \typ{timeit?} for help) + \item IPython lets you debug and profile code via the \typ{run} + macro (type \typ{run?} on the prompt to learn more) + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item \typ{dir([object])} function: attributes of given object + \item \typ{type(object)}: returns type information + \item \typ{str(), repr()}: convert object to string representation + \item \typ{isinstance, issubclass} + \item \typ{assert} statements let you do debugging assertions in + code + \item \typ{csv} module: reading and writing CSV files + \item \typ{pickle}: lets you save and load Python objects + (\alert{serialization}) + \item \typ{sys.argv}: command line arguments + \item \typ{os.path}: common path manipulations + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Test driven development (TDD)} + \begin{itemize} + \item Why? + \begin{itemize} + + \item Forces you to write reusable code! + + \item Think about the API + + \item More robust + + \item Makes refactoring very easy + + \end{itemize} + \item How? Python offers three major ways of doing this + \begin{itemize} + \item doctest + \item unittest + \item nosetest (and similar like py.test) + \end{itemize} + + \item Test every piece of functionality you offer + + \item This isn't a formal introduction but more a practical one + + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Unit test} +\begin{lstlisting} +import unittest + +class MyTestCase(unittest.TestCase): + def setUp(self): + # Called *before* each test_* + def tearDown(self): + # Called *after* each test_* + def test_something(self): + "docstring" + # Test code. + self.assertEqual(x, y) + self.assertRaises(ValueError, func, arg1, arg2 ...) + +if __name__ == '__main__': + unittest.main() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Nosetest} +\begin{lstlisting} +import particle +def test_particle(): + # Use asserts here. + p = particle.Particle(1.0) + assert p.property[0] == 1.0 + assert p.property[2] == 0.0 + +if __name__ == '__main__': + import nose + nose.main() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Testing} + \begin{itemize} + \item More details: see library reference and search for nosetest + \end{itemize} +\end{frame} + +\section{Numerics \& Plotting} + +\subsection{NumPy Arrays} + +\newcommand{\num}{\texttt{numpy}} + +\begin{frame} + \frametitle{The \num\ module} + \begin{itemize} + \item Manipulating large Python lists for scientific computing is + \alert{slow} + \item Most complex computations can be reduced to a few standard + operations + \item The \num\ module provides: + \begin{itemize} + \item An efficient and powerful array type for various common data + types + \item Abstracts out the most commonly used standard operations on + arrays + \end{itemize} + \item Numeric was the first, then came \texttt{numarray}. + \texttt{numpy} is the latest and is the future + \item This course uses \num\ and only covers the absolute basics + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Basic concepts} + \begin{itemize} + \item \num\ arrays are of a fixed size (\typ{arr.size}) and have the + same type (\typ{arr.dtype}) + \item \num\ arrays may have arbitrary dimensionality + \item The \typ{shape} of an array is the extent (length) of the + array along each dimension + \item The \typ{rank(arr)} of an array is the ``dimensionality'' of the + array + \item The \typ{arr.itemsize} is the number of bytes (8-bits) used for + each element of the array + \item \alert{Note:} The \typ{shape} and \typ{rank} may change as + long as the \typ{size} of the array is fixed + \item \alert{Note:} \typ{len(arr) != arr.size} in general + \item \alert{Note:} By default array operations are performed + \alert{elementwise} + \item Indices start from 0 + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Examples of \num} +\begin{lstlisting} +# Simple array math example +>>> from numpy import * +>>> a = array([1,2,3,4]) +>>> b = array([2,3,4,5]) +>>> a + b # Element wise addition! +array([3, 5, 7, 9]) + +>>> print pi, e # Pi and e are defined. +3.14159265359 2.71828182846 +# Create array from 0 to 10 +>>> x = arange(0.0, 10.0, 0.05) +>>> x *= 2*pi/10 # multiply array by scalar value +array([ 0.,0.0314,...,6.252]) +# apply functions to array. +>>> y = sin(x) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More examples of \num} +\vspace*{-8pt} +\begin{lstlisting} +# Size, shape, rank, type etc. +>>> x = array([1., 2, 3, 4]) +>>> size(x) +4 +>>> x.dtype # or x.dtype.char +'d' +>>> x.shape +(4,) +>>> print rank(x), x.itemsize +1 8 +>>> x.tolist() +[1.0, 2.0, 3.0, 4.0] +# Array indexing +>>> x[0] = 10 +>>> print x[0], x[-1] +10.0 4.0 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Multi-dimensional arrays} +\begin{lstlisting} +>>> a = array([[ 0, 1, 2, 3], +... [10,11,12,13]]) +>>> a.shape # (rows, columns) +(2, 4) +# Accessing and setting values +>>> a[1,3] +13 +>>> a[1,3] = -1 +>>> a[1] # The second row +array([10,11,12,-1]) + +# Flatten/ravel arrays to 1D arrays +>>> a.flat # or ravel(a) +array([0,1,2,3,10,11,12,-1]) +# Note: flat references original memory +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Slicing arrays} +\begin{lstlisting} +>>> a = array([[1,2,3], [4,5,6], [7,8,9]]) +>>> a[0,1:3] +array([2, 3]) +>>> a[1:,1:] +array([[5, 6], + [8, 9]]) +>>> a[:,2] +array([3, 6, 9]) +# Striding... +>>> a[0::2,0::2] +array([[1, 3], + [7, 9]]) +# All these slices are references to the same memory! +\end{lstlisting} +\end{frame} + +% \begin{frame}[fragile] +% \frametitle{Array types and typecodes} +% \begin{tabular}[c]{|c|c|p{2.75in}|} +% \hline +% Character & Bits (bytes) & Type name \\ +% \hline +% D & 128 (16) & \typ{Complex, Complex64}\\ +% F & 64 (8) & \typ{Complex0, Complex8, Complex16} \\ +% d & 64 (8) & \typ{Float, Float64} \\ +% f & 32 (4) & \typ{Float0, Float8, Float16} \\ +% i & 32 (4) & \typ{Int32} \\ +% l & 32 (4) & \typ{Int} \\ +% O & 4 (1) & \typ{PyObject} \\ +% %b 8 (1) UnsignedInt8 +% %1 (one) 8 (1) Int8 +% %s 16 (2) Int16 +% \hline +% \end{tabular} +% \begin{lstlisting} +% # Examples +% >>> f = array([1,2,3], Float32) +% >>> c = array([1,2,3], Complex32) +% >>> print f, c +% [ 1. 2. 3.] [ 1.+0.j 2.+0.j 3.+0.j] +% \end{lstlisting} +% \end{frame} + +\begin{frame}[fragile] + \frametitle{Array creation functions} + \begin{itemize} + \item \typ{array(object, dtype=None, copy=1,order=None, subok=0,ndmin=0)} + \item \typ{arange(start, stop=None, step=1, dtype=None)} + \item \typ{linspace(start, stop, num=50, endpoint=True, retstep=False)} + \item \typ{ones(shape, dtype=None, order='C')} + \item \typ{zeros((d1,...,dn),dtype=float,order='C')} + \item \typ{identity(n)} + \item \typ{empty((d1,...,dn),dtype=float,order='C')} + \item \typ{ones\_like(x)}, \typ{zeros\_like(x)}, \typ{empty\_like(x)} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Array math} + \begin{itemize} + \item Basic \alert{elementwise} math (given two arrays \typ{a, b}): + \begin{itemize} + \item \typ{a + b $\rightarrow$ add(a, b)} + \item \typ{a - b, $\rightarrow$ subtract(a, b)} + \item \typ{a * b, $\rightarrow$ multiply(a, b)} + \item \typ{a / b, $\rightarrow$ divide(a, b)} + \item \typ{a \% b, $\rightarrow$ remainder(a, b)} + \item \typ{a ** b, $\rightarrow$ power(a, b)} + \end{itemize} + \item Inplace operators: \typ{a += b}, or \typ{add(a, b, + a)} etc. + \item Logical operations: \typ{equal (==)}, \typ{not\_equal (!=)}, + \typ{less (<)}, \typ{greater (>)} etc. + \item Trig and other functions: \typ{sin(x), arcsin(x), sinh(x), + exp(x), sqrt(x)} etc. + \item \typ{sum(x, axis=0), product(x, axis=0)}: sum and product of array elements + \item \typ{dot(a, b)} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Advanced} + \begin{itemize} + \item Only scratched the surface of \num + \item Ufunc methods: \typ{reduce, accumulate, outer, reduceat} + \item Typecasting + \item More functions: \typ{take, choose, where, compress, + concatenate} + \item Array broadcasting and \typ{None} + \end{itemize} +\end{frame} + +\subsection{Plotting: Matplotlib} + +\begin{frame} + \frametitle{About \texttt{matplotlib}} + \begin{itemize} + \item Easy to use, scriptable, ``Matlab-like'' 2D plotting + \item Publication quality figures and interactive capabilities + \item Plots, histograms, power spectra, bar charts, errorcharts, + scatterplots, etc. + \item Also does polar plots, maps, contours + \item Support for simple \TeX\ markup + \item Multiple output backends (images, EPS, SVG, wx, Agg, Tk, GTK) + \item Cross-platform: Linux, Win32, Mac OS X + \item Good idea to use via IPython: \typ{ipython -pylab} + \item From scripts use: \typ{import pylab} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{More information} + \begin{itemize} + \item More information here: \url{http://matplotlib.sf.net} + \item \url{http://matplotlib.sf.net/tutorial.html} + \item \url{http://matplotlib.sf.net/screenshots.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting with \texttt{matplotlib}} +\begin{lstlisting} +>>> x = arange(0, 2*pi, 0.05) +>>> plot(x, sin(x)) # Same as plot(x, sin(x), 'b-') +>>> plot(x, sin(x), 'ro') +>>> axis([0,2*pi, -1,1]) +>>> xlabel(r'$\chi$', color='g') +>>> ylabel(r'sin($\chi$)', color='r') +>>> title('A simple figure', fontsize=20) +>>> savefig('/tmp/test.eps') +# Multiple plots in one figure +>>> t = arange(0.0, 5.2, 0.2) +# red dashes, blue squares and green triangles +>>> plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting \ldots} +\begin{lstlisting} +# Set properties of objects: +>>> plot(x, sin(x), linewidth=2.0, color='r') +>>> l, = plot(x, sin(x)) +>>> setp(l, linewidth=2.0, color='r') +>>> l.set_linewidth(2.0); l.set_color('r') +>>> draw() # Redraws current figure. +>>> setp(l) # Prints available properties +>>> close() # Closes the figure. +# Multiple figures: +>>> figure(1); plot(x, sin(x)) +>>> figure(2); plot(x, tanh(x)) +>>> figure(1); title('Easy as 1,2,3') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting \ldots} +\begin{lstlisting} +>>> figure(1) +>>> subplot(211) # Same as subplot(2, 1, 1) +>>> plot(x, cos(5*x)*exp(-x)) +>>> subplot(2, 1, 2) +>>> plot(x, cos(5*x), 'r--', label='cosine') +>>> plot(x, sin(5*x), 'g--', label='sine') +>>> legend() # Or legend(['cosine', 'sine']) +>>> text(1,0, '(1,0)') +>>> axes = gca() # Current axis +>>> fig = gcf() # Current figure +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{X-Y plot} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/xyplot} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +t1 = arange(0.0, 5.0, 0.1) +t2 = arange(0.0, 5.0, 0.02) +t3 = arange(0.0, 2.0, 0.01) +subplot(211) +plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', + t2, cos(2*pi*t2)*exp(-t2), 'k') +grid(True) +title('A tale of 2 subplots') +ylabel('Damped') +subplot(212) +plot(t3, cos(2*pi*t3), 'r--') +grid(True) +xlabel('time (s)') +ylabel('Undamped') +\end{lstlisting} + \end{block} + \end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Errorbar} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/errorbar} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +t = arange(0.1, 4, 0.1) +s = exp(-t) +e = 0.1*abs(randn(len(s))) +f = 0.1*abs(randn(len(s))) +g = 2*e +h = 2*f +errorbar(t, s, [e,g], f, fmt='o') +xlabel('Distance (m)') +ylabel('Height (m)') +title('Mean and standard error '\ + 'as a function of distance') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Semi-log and log-log plots} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/log} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +dt = 0.01 +t = arange(dt, 20.0, dt) +subplot(311) +semilogy(t, exp(-t/5.0)) +ylabel('semilogy') +grid(True) +subplot(312) +semilogx(t, sin(2*pi*t)) +ylabel('semilogx') +grid(True) +# minor grid on too +gca().xaxis.grid(True, which='minor') +subplot(313) +loglog(t, 20*exp(-t/10.0), basex=4) +grid(True) +ylabel('loglog base 4 on x') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Histogram} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/histogram} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +mu, sigma = 100, 15 +x = mu + sigma*randn(10000) +# the histogram of the data +n, bins, patches = hist(x, 100, normed=1) +# add a 'best fit' line +y = normpdf( bins, mu, sigma) +l = plot(bins, y, 'r--', linewidth=2) +xlim(40, 160) +xlabel('Smarts') +ylabel('P') +title(r'$\rm{IQ:}\/ \mu=100,\/ \sigma=15$') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Bar charts} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/barchart} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +N = 5 +menMeans = (20, 35, 30, 35, 27) +menStd = ( 2, 3, 4, 1, 2) +# the x locations for the groups +ind = arange(N) +# the width of the bars +width = 0.35 +p1 = bar(ind, menMeans, width, + color='r', yerr=menStd) +womenMeans = (25, 32, 34, 20, 25) +womenStd = ( 3, 5, 2, 3, 3) +p2 = bar(ind+width, womenMeans, width, + color='y', yerr=womenStd) +ylabel('Scores') +title('Scores by group and gender') +xticks(ind+width, + ('G1', 'G2', 'G3', 'G4', 'G5')) +xlim(-width,len(ind)) +yticks(arange(0,41,10)) +legend((p1[0], p2[0]), + ('Men', 'Women'), shadow=True) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Pie charts} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.4in} + \includegraphics[height=2.0in, interpolate=true]{data/piechart} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +# make a square figure and axes +figure(1, figsize=(8,8)) +ax = axes([0.1, 0.1, 0.8, 0.8]) +labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' +fracs = [15,30,45, 10] +explode=(0, 0.05, 0, 0) +pie(fracs, explode=explode, labels=labels, + autopct='%1.1f%%', shadow=True) +title('Raining Hogs and Dogs', + bbox={'facecolor':'0.8', 'pad':5}) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Scatter plots} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.4in} + \includegraphics[height=2in, interpolate=true]{data/scatter} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +N = 30 +x = 0.9*rand(N) +y = 0.9*rand(N) +# 0 to 10 point radiuses +area = pi*(10 * rand(N))**2 +volume = 400 + rand(N)*450 +scatter(x,y,s=area, marker='o', c=volume, + alpha=0.75) +xlabel(r'$\Delta_i$', size='x-large') +ylabel(r'$\Delta_{i+1}$', size='x-large') +title(r'Volume and percent change') +grid(True) +colorbar() +savefig('scatter') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Polar} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/polar} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +figure(figsize=(8,8)) +ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, + axisbg='#d5de9c') +r = arange(0,1,0.001) +theta = 2*2*pi*r +polar(theta, r, color='#ee8d18', lw=3) +# the radius of the grid labels +setp(ax.thetagridlabels, y=1.075) +title(r"$\theta=4\pi r", fontsize=20) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Contours} + \begin{columns} + \column{0.45\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/contour} + \column{0.525\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +x = arange(-3.0, 3.0, 0.025) +y = arange(-2.0, 2.0, 0.025) +X, Y = meshgrid(x, y) +Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) +# difference of Gaussians +Z = 10.0 * (Z2 - Z1) +im = imshow(Z, interpolation='bilinear', + origin='lower', + cmap=cm.gray, extent=(-3,3,-2,2)) +levels = arange(-1.2, 1.6, 0.2) +# label every second level +clabel(CS, levels[1::2], inline=1, + fmt='%1.1f', fontsize=14) +CS = contour(Z, levels, + origin='lower', + linewidths=2, + extent=(-3,3,-2,2)) +# make a colorbar for the contour lines +CB = colorbar(CS, shrink=0.8, extend='both') +title('Lines with colorbar') +hot(); flag() +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Velocity vectors} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/quiver} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +X,Y = meshgrid(arange(0,2*pi,.2), + arange(0,2*pi,.2) ) +U = cos(X) +V = sin(Y) +Q = quiver(X[::3, ::3], Y[::3, ::3], + U[::3, ::3], V[::3, ::3], + color='r', units='x', + linewidths=(2,), + edgecolors=('k'), + headaxislength=5 ) +qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', + fontproperties= + {'weight': 'bold'}) +axis([-1, 7, -1, 7]) +title('triangular head; scale '\ + 'with x view; black edges') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Maps} + \includegraphics[height=2.5in, interpolate=true]{data/plotmap} + \begin{center} + \tiny + For details see \url{http://matplotlib.sourceforge.net/screenshots/plotmap.py} + \end{center} +\end{frame} + + +\subsection{SciPy} + +\begin{frame} + \frametitle{Using \texttt{SciPy}} + \begin{itemize} + \item SciPy is Open Source software for mathematics, science, and + engineering + \item \typ{import scipy} + \item Built on NumPy + \item Provides modules for statistics, optimization, integration, + linear algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + \item Used widely by scientists world over + \item Details are beyond the scope of this tutorial + \end{itemize} +\end{frame} + +\section{Standard library} + +\subsection{Quick Tour} + +\begin{frame} + \frametitle{Standard library} + \begin{itemize} + \item Very powerful + \item ``Batteries included'' + \item Example standard modules taken from the tutorial + \begin{itemize} + \item Operating system interface: \typ{os} + \item System, Command line arguments: \typ{sys} + \item Regular expressions: \typ{re} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib2}, \typ{smtplib} + \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, + \typ{zipfile}, and \typ{tarfile} + \item Unit testing: \typ{doctest} and \typ{unittest} + \item And a whole lot more! + \end{itemize} + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import os +>>> os.system('date') +Fri Jun 10 22:13:09 IST 2005 +0 +>>> os.getcwd() +'/home/prabhu' +>>> os.chdir('/tmp') +>>> import os +>>> dir(os) +<returns a list of all module functions> +>>> help(os) +<extensive manual page from module's docstrings> +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import sys +>>> # Print the list of command line args to Python +... print sys.argv +[''] +>>> import re # Regular expressions +>>> re.findall(r'\bf[a-z]*', +... 'which foot or hand fell fastest') +['foot', 'fell', 'fastest'] +>>> re.sub(r'(\b[a-z]+) \1', r'\1', +... 'cat in the the hat') +'cat in the hat' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import math +>>> math.cos(math.pi / 4.0) +0.70710678118654757 +>>> math.log(1024, 2) +10.0 +>>> import random +>>> random.choice(['apple', 'pear', 'banana']) +'pear' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import urllib2 +>>> f = urllib2.urlopen('http://www.python.org/') +>>> print f.read(100) +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<?xml-stylesheet href="./css/ht2html +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import zlib +>>> s = 'witch which has which witches wrist watch' +>>> len(s) +41 +>>> t = zlib.compress(s) +>>> len(t) +37 +>>> zlib.decompress(t) +'witch which has which witches wrist watch' +>>> zlib.crc32(t) +-1438085031 +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Introduced Python + \item Basic syntax + \item Basic types and data structures + \item Control flow + \item Functions + \item Modules + \item Exceptions + \item Classes + \item Standard library + \end{itemize} +\end{frame} + +\end{document} + +\subsection{Basic data structures} +\begin{frame}{Lists} + \begin{itemize} + \item \texttt{species = [ 'humans', 'orcs', 'elves', 'dwarves' ]} + \item \texttt{ ids = [ 107, 109, 124, 141, 142, 144 ]} + \item \texttt{ oneliners = [ 'I will be back', 'Do or do not! No try!!', 42 ] } + \end{itemize} + + \begin{block}{List operations} + ids + [ 100, 102 ]\\ + species.append( 'unicorns')\\ + print oneliners[ 1 ]\\ + look up \alert{docs.python.org/tutorial/datastructures.html} + \end{block} +\end{frame} +\end{document} +\section{Python Tutorial} +\subsection{Preliminaries} +\begin{frame} + \frametitle{Using the interpreter} + \begin{itemize} + \item Starting up: \typ{python} or \typ{ipython} + \item Quitting: \typ{Control-D} or \typ{Control-Z} (on Win32) + \item Can use it like a calculator + \item Can execute one-liners via the \typ{-c} option: + \typ{python -c "print 'hello world'"} + \item Other options via \typ{python -h} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{IPython} + \begin{itemize} + \item Recommended interpreter, IPython: + \url{http://ipython.scipy.org} + \item Better than the default Python shell + \item Supports tab completion by default + \item Easier object introspection + \item Shell access! + \item Command system to allow extending its own behavior + \item Supports history (across sessions) and logging + \item Can be embedded in your own Python code + \item Support for macros + \item A flexible framework for your own custom interpreter + \item Other miscellaneous conveniences + \item We'll get back to this later + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic IPython features} + \begin{itemize} + \item Startup: \verb+ipython [options] files+ + \begin{itemize} + \item \verb+ipython [-wthread|-gthread|-qthread]+: + Threading modes to support wxPython, pyGTK and Qt + \item \verb+ipython -pylab+: Support for matplotlib + \end{itemize} + \item TAB completion: + \begin{itemize} + \item Type \verb+object_name.<TAB>+ to see list of options + \item Also completes on file and directory names + \end{itemize} + \item \verb+object?+ shows docstring/help for any Python object + \item \verb+object??+ presents more docs (and source if possible) + \item Debugging with \verb+%pdb+ magic: pops up pdb on errors + \item Access history (saved over earlier sessions also) + \begin{itemize} + \item Use \texttt{<UpArrow>}: move up history + \item Use \texttt{<Ctrl-r> string}: search history backwards + \item Use \texttt{Esc >}: get back to end of history + \end{itemize} + \item \verb+%run [options] file[.py]+ lets you run Python code + \end{itemize} +\end{frame} +% LocalWords: BDFL Guido Rossum PSF Nokia OO Zope CMS RedHat SciPy MayaVi spam +% LocalWords: IPython ipython stdin TypeError dict int elif PYTHONPATH IOError +% LocalWords: namespace Namespaces SyntaxError ZeroDivisionError NameError str +% LocalWords: ValueError subclassed def + + + \item Types are of two kinds: \alert{mutable} and \alert{immutable} + \item Immutable types: numbers, strings, \typ{None} and tuples + \item Immutables cannot be changed ``in-place'' + \item Mutable types: lists, dictionaries, instances, etc. + \item Mutable objects can be ``changed'' + \end{itemize} + + +\begin{frame} + \frametitle{Important!} + \begin{itemize} + \item Assignment to an object is by reference + \item Essentially, \alert{names are bound to objects} + \end{itemize} +\end{frame} + + +\end{document} +\begin{frame}[fragile] + \frametitle{Dictionaries} + \begin{itemize} + \item Associative arrays/mappings + \item Indexed by ``keys'' (keys must be immutable) + \item \typ{dict[key] = value} + \item \typ{keys()} returns all keys of the dict + \item \typ{values()} returns the values of the dict + \item \verb+has_key(key)+ returns if \typ{key} is in the dict + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries: example} + \begin{lstlisting} +>>> tel = {'jack': 4098, 'sape': 4139} +>>> tel['guido'] = 4127 +>>> tel +{'sape': 4139, 'guido': 4127, 'jack': 4098} +>>> tel['jack'] +4098 +>>> del tel['sape'] +>>> tel['irv'] = 4127 +>>> tel +{'guido': 4127, 'irv': 4127, 'jack': 4098} +>>> tel.keys() +['guido', 'irv', 'jack'] +>>> tel.has_key('guido') +True + \end{lstlisting} +\end{frame} + +\subsection{Control flow, functions} + + + +\begin{frame}[fragile] + \frametitle{\typ{If} example} + \begin{lstlisting} +>>> a = ['cat', 'window', 'defenestrate'] +>>> if 'cat' in a: +... print "meaw" +... +meaw +>>> pets = {'cat': 1, 'dog':2, 'croc': 10} +>>> if 'croc' in pets: +... print pets['croc'] +... +10 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for} example} + \begin{lstlisting} +>>> a = ['cat', 'window', 'defenestrate'] +>>> for x in a: +... print x, len(x) +... +cat 3 +window 6 +defenestrate 12 +>>> knights = {'gallahad': 'the pure', +... 'robin': 'the brave'} +>>> for k, v in knights.iteritems(): +... print k, v +... +gallahad the pure +robin the brave +\end{lstlisting} +\end{frame} diff --git a/day1/Session-1.tex~ b/day1/Session-1.tex~ new file mode 100755 index 0000000..ccc22a3 --- /dev/null +++ b/day1/Session-1.tex~ @@ -0,0 +1,2752 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Tutorial slides on Python. +% +% Author: Prabhu Ramachandran <prabhu at aero.iitb.ac.in> +% Copyright (c) 2005-2008, Prabhu Ramachandran +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} +%\documentclass[draft]{beamer} +%\documentclass[compress,handout]{beamer} +%\usepackage{pgfpages} +%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] + +% Modified from: generic-ornate-15min-45min.de.tex +\mode<presentation> +{ + \usetheme{Warsaw} + \useoutertheme{split} + \setbeamercovered{transparent} +} + +\usepackage[english]{babel} +\usepackage[latin1]{inputenc} +%\usepackage{times} +\usepackage[T1]{fontenc} + +% Taken from Fernando's slides. +\usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} +\usepackage[scaled=.95]{helvet} + +\definecolor{darkgreen}{rgb}{0,0.5,0} + +\usepackage{listings} +\lstset{language=Python, + basicstyle=\ttfamily, + commentstyle=\color{red}\itshape, + stringstyle=\color{darkgreen}, + showstringspaces=false, + keywordstyle=\color{blue}\bfseries} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Macros +\setbeamercolor{emphbar}{bg=blue!20, fg=black} +\newcommand{\emphbar}[1] +{\begin{beamercolorbox}[rounded=true]{emphbar} + {#1} + \end{beamercolorbox} +} +\newcounter{time} +\setcounter{time}{0} +\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} + +\newcommand{\typ}[1]{\texttt{#1}} + +\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } + +%%% This is from Fernando's setup. +% \usepackage{color} +% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} +% % Use and configure listings package for nicely formatted code +% \usepackage{listings} +% \lstset{ +% language=Python, +% basicstyle=\small\ttfamily, +% commentstyle=\ttfamily\color{blue}, +% stringstyle=\ttfamily\color{orange}, +% showstringspaces=false, +% breaklines=true, +% postbreak = \space\dots +% } + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Basic Python]{Python:\\A great programming toolkit} + +\author[Asokan \& Prabhu] {Asokan Pichai\\Prabhu Ramachandran} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {10, August 2009} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} +%\logo{\pgfuseimage{iitmlogo}} + + +%% Delete this, if you do not want the table of contents to pop up at +%% the beginning of each subsection: +\AtBeginSubsection[] +{ + \begin{frame}<beamer> + \frametitle{Outline} + \tableofcontents[currentsection,currentsubsection] + \end{frame} +} + + +% If you wish to uncover everything in a step-wise fashion, uncomment +% the following command: +%\beamerdefaultoverlayspecification{<+->} + +%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% DOCUMENT STARTS +\begin{document} + +\begin{frame} + \titlepage +\end{frame} +\begin{frame} + {Acknowledgements} + \begin{center} + This program is conducted by\\ + IIT, Bombay\\ + through CDEEP\\as part of the open source initiatives\\ + under the aegis of\\ + \alert{National Mission on Education through ICT,} \\ + Ministry of HRD. + \end{center} +\end{frame} + +\begin{frame} + \frametitle{Outline} + \tableofcontents + % You might wish to add the option [pausesections] +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TODO +% +% * Add slide on Python packages (modules) +% * Add slides on reference counting. + +\section{Agenda} +\begin{frame}{About the Workshop} + \begin{description} + \item[Day 1, Session 1] Sat 9:30--11:00 + \item[Day 1, Session 2] Sat 11:15--12:45 + \item[Day 1, Session 3] Sat 13:45--15:15 + \item[Day 1, Session 4] Sat 15:30--17:00 + \item[Day 2, Session 1] Sun 9:30--11:00 + \item[Day 2, Session 2] Sun 11:15--12:45 + \item[Day 2, Session 3] Sun 13:45--15:15 + \item[Day 2, Session 4] Sun 15:30--17:00 + \end{description} +\end{frame} + +\section{Agenda} +\begin{frame}{About the Workshop} + \begin{block}{Goal of the workshop} + At the end of this program, successful participants will be able to use python as their scripting and problem solving language. Aimed at Engg. students--focus on basic numerics and plotting-- but should serve a similar purpose for others. + \end{block} +\end{frame} + +\begin{frame}{Checklist} + Let us verify that all of us are having the same (similar) tools and environment + \begin{description} + \item[python] Type python at the command line. Do you see version 2.5 or later? + \item[IPython] Is IPython available? + \item[Editor] Which editor? scite, vim, emacs, \ldots + \end{description} +\end{frame} + +\section{Overview} +\begin{frame}{Session 1} + \begin{itemize} + \item Introduction and motivation + \item Using the interpreter(s) + \item Basic data types: int, float, string + \item Basic data structures: list + \item Basic console IO: \texttt{raw\_input(), print} + \item Basic control flow: \texttt{if, while} + \item Problem set 1 + \item Functions $\rightarrow$ Problem set 2 + \item lists, \texttt{for} $\rightarrow$ Problem set 3 + \item IO, Modules $\rightarrow$ Problem sets 4,5, \ldots + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Introduction} + \begin{itemize} + \item Creator and BDFL: Guido van Rossum + \item Conceived in December 1989 + \item ``Python'' as in Monty Python's Flying Circus + \item Current stable version of Python is 2.6.x + \item PSF license (like BSD: no strings attached) + \item Highly cross platform + \item Runs on the Nokia series 60! + \item \alert{Philosophy:} Simple and complete by design + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Resources} + \begin{itemize} + \item Part of many GNU/Linux distributions + \item Web: \url{http://www.python.org} + \item Doc: \url{http://www.python.org/doc} + \item Free Tutorials: + \begin{itemize} + \item Official Python tutorial: \url{http://docs.python.org/tut/tut.html} + \item Byte of Python: \url{http://www.byteofpython.info/} + \item Dive into Python: \url{http://diveintopython.org/} + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Why Python?} + \begin{itemize} + \item Designed to be readable and easy to use + \item High level, interpreted, modular, OO + \item Much faster development cycle + \item Powerful interactive environment + \item Rapid application development + \item Rich standard library and modules + \item Interfaces well with C++, C and FORTRAN + \item \alert{More than a math package $\Rightarrow$ some extra work compared to math packages} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Use cases} + \begin{itemize} + \item NASA: Space Shuttle Mission Design + \item AstraZeneca: Collaborative Drug Discovery + \item ForecastWatch.com: Helps Meteorologists + \item Industrial Light \& Magic: Runs on Python + \item Zope: Commercial grade Toolkit + \item Plone: Professional high feature CMS + \item RedHat: install scripts, sys-admin tools + \item Django: A great web application framework + \item Google: A strong python shop + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{To sum up, python is\ldots} + \begin{itemize} + \item dynamically typed, interpreted $\rightarrow$ rapid testing/prototyping + \item powerful, very high level + \item has full introspection + \item Did we mention powerful? + \end{itemize} + \begin{block}{But \ldots} + may be wanting in performance. specialised resources such as SWIG, \alert{Cython} are available + \end{block} + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 15m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\section{Python} + +\subsection{Getting Started} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> print 'Hello Python' +>>> print 3124 * 126789 +>>> 1786 % 12 +>>> 3124 * 126789 +>>> a = 3124 * 126789 +>>> big = 12345678901234567890 ** 3 +>>> verybig = big * big * big * big +>>> 12345**6, 12345**67, 12345**678 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> s = 'Hello ' +>>> p = 'World' +>>> s + p +>>> s * 12 +>>> s * s +>>> s + p * 12, (s + p)* 12 +>>> s * 12 + p * 12 +>>> 12 * s + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> 17/2 +>>> 17/2.0 +>>> 17.0/2 +>>> 17.0/8.5 +>>> int(17/2.0) +>>> float(17/2) +>>> str(17/2.0) +>>> round( 7.5 ) + \end{lstlisting} + \begin{block}{Mini exercise} + Round a float to the nearest integer, using \texttt{int()}? + \end{block} +\end{frame} + +\begin{frame}{Midi exercises} + \begin{center} + \begin{itemize} + \item What does this do? + \item \texttt{round(amount * 10) /10.0 } + \end{itemize} + \end{center} +\end{frame} + +\begin{frame}{More exercises?} + \begin{center} + \begin{block}{Round sums} + How to round a number to the nearest 5 paise?\\ + \begin{description} + \item[Remember] 17.23 $\rightarrow$ 17.25,\\ while 17.22 $\rightarrow$ 17.20\\ + \end{description} + How to round a number to the nearest 20 paise? + \end{block} + \end{center} +\end{frame} + +\begin{frame}[fragile] {A question of good style} + \begin{lstlisting} + amount = 12.68 + denom = 0.05 + nCoins = round(amount/denom) + rAmount = nCoins * denom + \end{lstlisting} + \pause + \begin{block}{Style Rule \#1} + Naming is 80\% of programming + \end{block} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item Case sensitive + \item Dynamically typed $\Rightarrow$ need not specify a type + \begin{lstlisting} +a = 1 +a = 1.1 +a = "Now I am a string!" + \end{lstlisting} + \item Comments: + \begin{lstlisting} +a = 1 # In-line comments +# Comment in a line to itself. +a = "# This is not a comment!" + \end{lstlisting} + \end{itemize} + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 30m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Data types} +\begin{frame} + \frametitle{Basic types} + \begin{itemize} + \item numbers: float, int, long, complex + \item strings + \item boolean + \end{itemize} + \begin{block}{Also to be discussed later} + tuples, lists, dictionaries, functions, objects\ldots + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Numbers} + \vspace*{-0.25in} + \begin{lstlisting} +>>> a = 1 # Int. +>>> l = 1000000L # Long +>>> e = 1.01325e5 # float +>>> f = 3.14159 # float +>>> c = 1+1j # Complex! +>>> print f*c/a +(3.14159+3.14159j) +>>> print c.real, c.imag +1.0 1.0 +>>> abs(c) +1.4142135623730951 +>>> abs( 8 - 9.5 ) +1.5 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Boolean} + \begin{lstlisting} +>>> t = True +>>> f = not t +False +>>> f or t +True +>>> f and t +False + \end{lstlisting} + \begin{block}{Try:} + NOT True\\ + not TRUE + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Relational and logical operators} + \begin{lstlisting} +>>> a, b, c = -1, 0, 1 +>>> a == b +False +>>> a <= b +True +>>> a + b != c +True +>>> a < b < c +True +>>> c >= a + b +True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Strings} + \begin{lstlisting} +s = 'this is a string' +s = 'This one has "quotes" inside!' +s = "I have 'single-quotes' inside!" +l = "A string spanning many lines\ +one more line\ +yet another" +t = """A triple quoted string does +not need to be escaped at the end and +"can have nested quotes" etc.""" + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More Strings} + \vspace*{-0.2in} + \begin{lstlisting} +>>> w = "hello" +>>> print w[0] + w[2] + w[-1] +hlo +>>> len(w) # guess what +5 +>>> s = u'Unicode strings!' +>>> # Raw strings (note the leading 'r') +... r_s = r'A string $\alpha \nu$' + \end{lstlisting} +\pause + \begin{lstlisting} +>>> w[0] = 'H' # Can't do that! +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: object does not support item assignment + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Let us switch to IPython} + Why? + \begin{block} + {Better help (and a lot more)} + Tab completion\\ + ?\\ + .?\\ + object.function? + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More on strings} + \begin{lstlisting} +In [1]: a = 'hello world' +In [2]: a.startswith('hell') +Out[2]: True +In [3]: a.endswith('ld') +Out[3]: True +In [4]: a.upper() +Out[4]: 'HELLO WORLD' +In [5]: a.upper().lower() +Out[5]: 'hello world' + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Still with strings} + \begin{lstlisting} +In [6]: a.split() +Out[6]: ['hello', 'world'] +In [7]: ''.join(['a', 'b', 'c']) +Out[7]: 'abc' +In [8] 'd' in ''.join( 'a', 'b', 'c') +Out[8]: False + \end{lstlisting} + \begin{block}{Try:} + \texttt{a.split( 'o' )}\\ + \texttt{'x'.join( a.split( 'o' ) )} + \end{block} +\end{frame} + +\begin{frame}[fragile]{Surprise! strings!!} + \begin{lstlisting} +In [11]: x, y = 1, 1.2 +In [12]: 'x is %s, y is %s' %(x, y) +Out[12]: 'x is 1, y is 1.234' + \end{lstlisting} + \begin{block}{Try:} + \texttt{'x is \%d, y is \%f' \%(x, y) }\\ + \texttt{'x is \%3d, y is \%4.2f' \%(x, y) } + \end{block} + \small +\url{docs.python.org/lib/typesseq-strings.html}\\ +\end{frame} + +\begin{frame} + {Interlude} + \begin{block} + {A classic problem} + How to interchange values of two variables? Please note that the type of either variable is unknown and it is not necessary that both be of the same type even! + \end{block} + \inctime{30} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 25 m+ Interlude break 5 mins, running 60m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Control flow} +\begin{frame} + \frametitle{Control flow constructs} + \begin{itemize} + \item \kwrd{if/elif/else}: branching + \item \kwrd{while}: looping + \item \kwrd{for}: iterating + \item \kwrd{break, continue}: modify loop + \item \kwrd{pass}: syntactic filler + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic conditional flow} + \begin{lstlisting} +In [21]: a = 7 +In [22]: b = 8 +In [23]: if a > b: + ....: print 'Hello' + ....: else: + ....: print 'World' + ....: + ....: +World + \end{lstlisting} + Let us switch to creating a file +\end{frame} + +\begin{frame} + {Creating python files} + \begin{itemize} + \item aka scripts + \item use your editor + \item Note that white space is the way to specify blocks! + \item extension \typ{.py} + \item run with \texttt{python hello.py} at the command line + \item in IPython\ldots + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{If...elif...else} example} +\begin{lstlisting} +x = int(raw_input("Enter an integer:")) +if x < 0: + print 'Be positive!' +elif x == 0: + print 'Zero' +elif x == 1: + print 'Single' +else: + print 'More' +\end{lstlisting} +\end{frame} + +\begin{frame}{Simple IO} + \begin{block} + {Console Input} + \texttt{raw\_input(}) waits for user input.\\Prompt string is optional.\\ + All keystrokes are Strings!\\\texttt{int()} converts string to int. + \end{block} + \begin{block} + {Console output} + \texttt{print} is straight forward. Major point to remember is the distinction between \texttt{print x} and \texttt{print x,} + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic looping} + \begin{lstlisting} +# Fibonacci series: +# the sum of two elements +# defines the next +a, b = 0, 1 +while b < 10: + print b, + a, b = b, a + b + +\end{lstlisting} +\typ{1 1 2 3 5 8}\\ +\alert{Recall it is easy to write infinite loops with \kwrd{while}} + \inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 80m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + \frametitle{Problem set 1} + \begin{itemize} + \item All the problems can be\\ + solved using \kwrd{if} and \kwrd{while} + \end{itemize} +\end{frame} + +\begin{frame}{Problem 1.1} + Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ +These are called $Armstrong$ numbers. +\end{frame} + +\begin{frame}{Problem 1.2 - Collatz sequence} +\begin{enumerate} + \item Start with an arbitrary (positive) integer. + \item If the number is even, divide by 2; if the number is odd multiply by 3 and add 1. + \item Repeat the procedure with the new number. + \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. +\end{enumerate} + Write a program that accepts the starting value and prints out the Collatz sequence. + +\end{frame} + +\begin{frame}{Problem 1.3 - Kaprekar's constant} + \begin{enumerate} + \item Take a four digit number--with at least two digits different. + \item Arrange the digits in ascending and descending order, giving A and D respectively. + \item Leave leading zeros in A! + \item Subtract A from D. + \item With the result, repeat from step 2. + \end{enumerate} + Write a program to accept a 4-digit number and display the progression to Kaprekar's constant. +\end{frame} + +\begin{frame}[fragile]{Problem 1.4} + Write a program that prints the following pyramid on the screen. + \begin{lstlisting} +1 +2 2 +3 3 3 +4 4 4 4 + \end{lstlisting} +The number of lines must be obtained from the user as input.\\ +\pause +When can your code fail? +\only<2->{\inctime{25}} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 25 m, running 105m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Functions} +\begin{frame}[fragile] +\frametitle{Functions: examples} + \begin{lstlisting} +def signum( r ): + """returns 0 if r is zero + -1 if r is negative + +1 if r is positive""" + if r < 0: + return -1 + elif r > 0: + return 1 + else: + return 0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: examples} + \begin{lstlisting} +def pad( n, size ): + """pads integer n with spaces + into a string of length size + """ + SPACE = ' ' + s = str( n ) + padSize = size - len( s ) + return padSize * SPACE + s + \end{lstlisting} +\pause +What about \%3d? +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} + \begin{lstlisting} +def what( n ): + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} +\begin{lstlisting} +def what( n ): + i = 1 + while i * i < n: + i += 1 + return i * i == n, i + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} + \begin{lstlisting} +def what( n, x ): + z = 1.0 + if n < 0: + x = 1.0 / x + n = -n + while n > 0: + if n % 2 == 1: + z *= x + n /= 2 + x *= x + return z + \end{lstlisting} +\end{frame} + +\begin{frame} + {Before writing a function} + \begin{itemize} + \item Builtin functions for various and sundry + \item \typ{abs, any, all, len, max, min} + \item \typ{pow, range, sum, type} + \item Refer here: + \url{http://docs.python.org/library/functions.html} + \end{itemize} + \inctime{15} +\end{frame} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 120m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame}{Problem set 2} + The focus is on writing functions and calling them. +\end{frame} + +\begin{frame}{Problem 2.1} + Write a function to return the gcd of two numbers. +\end{frame} + +\begin{frame}{Problem 2.2} +A pythagorean triad $(a,b,c)$ has the property $a^2 + b^2 = c^2$.\\By primitive we mean triads that do not `depend' on others. For example, (4,3,5) is a variant of (3,4,5) and hence is not primitive. And (10,24,26) is easily derived from (5,12,13) and should not be displayed by our program. \\ +Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100 +\end{frame} + +\begin{frame}{Problem 2.3} + Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\\For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square). +\end{frame} + +\begin{frame}{Problem 2.4} + The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. For example, the aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.\\ + Write a function that returns the aliquot number of a given number. +\end{frame} + +\begin{frame}{Problem 2.5} + A pair of numbers (a, b) is said to be \alert{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ + Example: \texttt{220, 284}\\ + Write a program that prints all five digit amicable pairs. + \inctime{30} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 30 m, running 150m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Lists} + +\begin{frame}[fragile] + \frametitle{List creation and indexing} +\begin{lstlisting} +>>> a = [] # An empty list. +>>> a = [1, 2, 3, 4] # More useful. +>>> len(a) +4 +>>> a[0] + a[1] + a[2] + a[-1] +10 +\end{lstlisting} + \begin{itemize} + \item Indices start with ? + \item Negative indices indicate ? + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: slices} + \begin{itemize} + \item Slicing is a basic operation + \item \typ{list[initial:final:step]} + \item The step is optional + \end{itemize} +\begin{lstlisting} +>>> a[1:3] # A slice. +[2, 3] +>>> a[1:-1] +[2, 3, 4] +>>> a[1:] == a[1:-1] +False +\end{lstlisting} +Explain last result +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: more slices} +\begin{lstlisting} +>>> a[0:-1:2] # Notice the step! +[1, 3] +>>> a[::2] +[1, 3] +>>> a[-1::-1] +\end{lstlisting} +What do you think the last one will do? + \emphbar{Note: Strings also use same indexing and slicing.} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: examples} +\begin{lstlisting} +>>> a = [1, 2, 3, 4] +>>> a[:2] +[1, 3] +>>> a[0:-1:2] +[1, 3] +\end{lstlisting} +\pause +\alert{Lists are mutable (unlike strings)} +\begin{lstlisting} +>>> a[1] = 20 +>>> a +[1, 20, 3, 4] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists are mutable and heterogenous} +\begin{lstlisting} +>>> a = ['spam', 'eggs', 100, 1234] +>>> a[2] = a[2] + 23 +>>> a +['spam', 'eggs', 123, 1234] +>>> a[0:2] = [1, 12] # Replace items +>>> a +[1, 12, 123, 1234] +>>> a[0:2] = [] # Remove items +>>> a.append( 12345 ) +>>> a +[123, 1234, 12345] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List methods} +\begin{lstlisting} +>>> a = ['spam', 'eggs', 1, 12] +>>> a.reverse() # in situ +>>> a +[12, 1, 'eggs', 'spam'] +>>> a.append(['x', 1]) +>>> a +[12, 1, 'eggs', 'spam', ['x', 1]] +>>> a.extend([1,2]) # Extend the list. +>>> a.remove( 'spam' ) +>>> a +[12, 1, 'eggs', ['x', 1], 1, 2] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List containership} + \begin{lstlisting} +>>> a = ['cat', 'dog', 'rat', 'croc'] +>>> 'dog' in a +True +>>> 'snake' in a +False +>>> 'snake' not in a +True +>>> 'ell' in 'hello world' +True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Tuples: immutable} +\begin{lstlisting} +>>> t = (0, 1, 2) +>>> print t[0], t[1], t[2], t[-1] +0 1 2 2 +>>> t[0] = 1 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: object does not support item + assignment +\end{lstlisting} +\begin{itemize} + \item Multiple return values are actually a tuple. + \item Exchange is tuple (un)packing +\end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{range()} function} + \begin{lstlisting} +>>> range(7) +[0, 1, 2, 3, 4, 5, 6] +>>> range( 3, 9) +[3, 4, 5, 6, 7, 8] +>>> range( 4, 17, 3) +[4, 7, 10, 13, 16] +>>> range( 5, 1, -1) +[5, 4, 3, 2] +>>> range( 8, 12, -1) +[] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for\ldots range(\ldots)} idiom} + \begin{lstlisting} +In [83]: for i in range(5): + ....: print i, i * i + ....: + ....: +0 0 +1 1 +2 4 +3 9 +4 16 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for}: the list companion} + + \begin{lstlisting} +In [84]: a = ['a', 'b', 'c'] +In [85]: for x in a: + ....: print x, chr( ord(x) + 10 ) + ....: +a k +b l +c m + \end{lstlisting} + Iterating over the list and not the index + reference\\ + what if you want the index? +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for}: the list companion} + \begin{lstlisting} +In [89]: for p, ch in enumerate( a ): + ....: print p, ch + ....: + ....: +0 a +1 b +2 c + \end{lstlisting} +Try: \typ{print enumerate(a)} +\inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 170m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + {Problem set 3} + As you can guess, idea is to use \kwrd{for}! +\end{frame} + +\begin{frame}{Problem 3.1} + Which of the earlier problems is simpler when we use \kwrd{for} instead of \kwrd{while}? +\end{frame} + +\begin{frame}{Problem 3.2} + Given an empty chessboard and one Bishop placed in any square, say (r, c), generate the list of all squares the Bishop could move to. +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.3} + + Given two real numbers \typ{a, b}, and an integer \typ{N}, write a + function named \typ{linspace( a, b, N)} that returns an ordered list + of \typ{N} points starting with \typ{a} and ending in \typ{b} and + equally spaced.\\ + + For example, \typ{linspace(0, 5, 11)}, should return, \\ +\begin{lstlisting} +[ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, + 3.0 , 3.5, 4.0 , 4.5, 5.0 ] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.4a (optional)} + +Use the \typ{linspace} function and generate a list of N tuples of the form\\ +\typ{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions,\begin{itemize} + \item \typ{f(x) = sin(x)} + \item \typ{f(x) = sin(x) + sin(10*x)}. +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.4b (optional)} + + Using the tuples generated earlier, determine the intervals where the roots of the functions lie. + + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 185m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{IO} + +\begin{frame}[fragile] + \frametitle{Simple tokenizing and parsing} + \begin{lstlisting} +s = """The quick brown fox jumped + over the lazy dog""" +for word in s.split(): + print word.capitalize() + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 4.1} + Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \\ + \begin{lstlisting} + [1,3,4,5,6,7,12,15,18,19,20,21] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File handling} +\begin{lstlisting} +>>> f = open('/path/to/file_name') +>>> data = f.read() # Read entire file. +>>> line = f.readline() # Read one line. +>>> f.close() # close the file. +\end{lstlisting} +Writing files +\begin{lstlisting} +>>> f = open('/path/to/file_name', 'w') +>>> f.write('hello world\n') +>>> f.close() +\end{lstlisting} +\begin{itemize} + \item Everything read or written is a string +\end{itemize} +\emphbar{Try \typ{file?} for more help} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File and \kwrd{for}} +\begin{lstlisting} +>>> f = open('/path/to/file_name') +>>> for line in f: +... print line +... +\end{lstlisting} +\end{frame} + +\begin{frame}{Problem 4.2} + The given file has lakhs of records in the form:\\ + \typ{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}\\ + Some entries may be empty. Read the data from this file and print the + name of the student with the maximum total marks. +\end{frame} + +\begin{frame}{Problem 4.3} + For the same data file compute the average marks in different + subjects, the student with the maximum mark in each subject and also + the standard deviation of the marks. Do this efficiently. + + \inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 205m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Modules} + +\begin{frame}[fragile] + {Modules} +\begin{lstlisting} +>>> sqrt(2) +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +NameError: name 'sqrt' is not defined +>>> import math +>>> math.sqrt(2) +1.4142135623730951 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {Modules} + \begin{itemize} + \item The \kwrd{import} keyword ``loads'' a module + \item One can also use: + \begin{lstlisting} +>>> from math import sqrt +>>> from math import * + \end{lstlisting} + \item What is the difference? + \item \alert{Use the later only in interactive mode} + \end{itemize} + \emphbar{Package hierarchies} + \begin{lstlisting} +>>> from os.path import exists + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Modules: Standard library} + \begin{itemize} + \item Very powerful, ``Batteries included'' + \item Some standard modules: + \begin{itemize} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib2}, \typ{smtplib} + \item System, Command line arguments: \typ{sys} + \item Operating system interface: \typ{os} + \item Regular expressions: \typ{re} + \item Compression: \typ{gzip}, \typ{zipfile}, and \typ{tarfile} + \item And a whole lot more! + \end{itemize} + \item Check out the Python Library reference: + \url{http://docs.python.org/library/} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + {Modules of special interest} + \begin{description}[matplotlibfor2d] + + \item[\typ{numpy}] Efficient, powerful numeric arrays + + \item[\typ{matplotlib}] Easy, interactive, 2D plotting + + \item[\typ{scipy}] statistics, optimization, integration, linear + algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + + \item[Mayavi] Easy, interactive, 3D plotting + + \end{description} +\end{frame} + +\begin{frame}[fragile] + {Creating your own modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \typ{.py} extension + \item This file becomes a module! + \item Accessible when in the current directory + \item Use \typ{cd} in IPython to change directory + + \item Naming your module + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- arith.py --- +def gcd(a, b): + if a%b == 0: return b + return gcd(b, a%b) +def lcm(a, b): + return a*b/gcd(a, b) +# ------------------ +>>> import arith +>>> arith.gcd(26, 65) +13 +>>> arith.lcm(26, 65) +130 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 5.1} + + Put all the functions you have written so far as part of the problems + into one module called \typ{iitb.py} and use this module from IPython. + +\inctime{20} +\end{frame} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 225m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + \frametitle{Did we meet the goal?} + \tableofcontents + % You might wish to add the option [pausesections] + \end{frame} + + \begin{frame} + {Tomorrow} + \begin{itemize} + \item Plotting: 2D, 3D + \item NumPy, SciPy + \item Dictionary, Set + \item Debugging + \item Testing + \item \ldots + \end{itemize} + 11:30--13:00 Discussion of answers to problems OPTIONAL + \end{frame} +\end{document} + + +\begin{frame}[fragile] + \frametitle{More on functions} + \begin{itemize} + \item Support default and keyword arguments + \item Scope of variables in the function is local + \item Mutable items are \alert{passed by reference} + \item First line after definition may be a documentation string + (\alert{recommended!}) + \item Function definition and execution defines a name bound to the + function + \item You \emph{can} assign a variable to a function! + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Functions: default arguments} + \begin{lstlisting} +def ask_ok(prompt, retries=4, complaint='Yes or no!'): + while True: + ok = raw_input(prompt) + if ok in ('y', 'ye', 'yes'): + return True + if ok in ('n', 'no', 'nop', 'nope'): + return False + retries = retries - 1 + if retries < 0: + raise IOError, 'bad user' + print complaint + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: keyword arguments} + \begin{lstlisting} +def parrot(voltage, state='a stiff', + action='voom', type='Norwegian Blue'): + print "-- This parrot wouldn't", action, + print "if you put", voltage, "Volts through it." + print "-- Lovely plumage, the", type + print "-- It's", state, "!" + +parrot(1000) +parrot(action = 'VOOOOOM', voltage = 1000000) +parrot('a thousand', state = 'pushing up the daisies') +parrot('a million', 'bereft of life', 'jump') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: arbitrary argument lists} + \begin{itemize} + \item Arbitrary number of arguments using \verb+*args+ or + \verb+*whatever+ + \item Keyword arguments using \verb+**kw+ + \item Given a tuple/dict how do you call a function? + \begin{itemize} + \item Using argument unpacking + \item For positional arguments: \verb+foo(*[5, 10])+ + \item For keyword args: \verb+foo(**{'a':5, 'b':10})+ + \end{itemize} + \end{itemize} +\begin{lstlisting} +def foo(a=10, b=100): + print a, b +def func(*args, **keyword): + print args, keyword +# Unpacking: +args = [5, 10] +foo(*args) +kw = {'a':5, 'b':10} +foo(**kw) +\end{lstlisting} +\end{frame} + +\subsection{Modules, exceptions, classes} + +\begin{frame} + \frametitle{Modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \typ{.py} extension + \item This file becomes a module! + \item Modules are searched in the following: + \begin{itemize} + \item Current directory + \item Standard: \typ{/usr/lib/python2.3/site-packages/} etc. + \item Directories specified in PYTHONPATH + \item \typ{sys.path}: current path settings (from the \typ{sys} + module) + \end{itemize} + \item The \typ{import} keyword ``loads'' a module + \item One can also use: + \mbox{\typ{from module import name1, name2, name2}}\\ + where \typ{name1} etc. are names in the module, ``module'' + \item \typ{from module import *} \ --- imports everything from module, + \alert{use only in interactive mode} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- foo.py --- +some_var = 1 +def fib(n): # write Fibonacci series up to n + """Print a Fibonacci series up to n.""" + a, b = 0, 1 + while b < n: + print b, + a, b = b, a+b +# EOF + +>>> import foo +>>> foo.fib(10) +1 1 2 3 5 8 +>>> foo.some_var +1 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Namespaces} + \begin{itemize} + \item A mapping from names to objects + \item Modules introduce a namespace + \item So do classes + \item The running script's namespace is \verb+__main__+ + \item A modules namespace is identified by its name + \item The standard functions (like \typ{len}) are in the + \verb+__builtin__+ namespace + \item Namespaces help organize different names and their bindings to + different objects + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Exceptions} + \begin{itemize} + \item Python's way of notifying you of errors + \item Several standard exceptions: \typ{SyntaxError}, \typ{IOError} + etc. + \item Users can also \typ{raise} errors + \item Users can create their own exceptions + \item Exceptions can be ``caught'' via \typ{try/except} blocks + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exception: examples} +\begin{lstlisting} +>>> 10 * (1/0) +Traceback (most recent call last): + File "<stdin>", line 1, in ? +ZeroDivisionError: integer division or modulo by zero +>>> 4 + spam*3 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +NameError: name 'spam' is not defined +>>> '2' + 2 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: cannot concatenate 'str' and 'int' objects +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exception: examples} +\begin{lstlisting} +>>> while True: +... try: +... x = int(raw_input("Enter a number: ")) +... break +... except ValueError: +... print "Invalid number, try again..." +... +>>> # To raise exceptions +... raise ValueError, "your error message" +Traceback (most recent call last): + File "<stdin>", line 2, in ? +ValueError: your error message +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: the big picture} + \begin{itemize} + \item Lets you create new data types + \item Class is a template for an object belonging to that class + \item Note: in Python a class is also an object + \item Instantiating a class creates an instance (an object) + \item An instance encapsulates the state (data) and behavior + (methods) + \item Allows you to define an inheritance hierarchy + \begin{itemize} + \item ``A Honda car \alert{is a} car.'' + \item ``A car \alert{is an} automobile.'' + \item ``A Python \alert{is a} reptile.'' + \end{itemize} + \item Programmers need to think OO + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: what's the big deal?} + \begin{itemize} + \item Lets you create objects that mimic a real problem being + simulated + \item Makes problem solving more natural and elegant + \item Easier to create code + \item Allows for code-reuse + \item Polymorphism + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Class definition and instantiation} + \begin{itemize} + \item Class definitions when executed create class objects + \item Instantiating the class object creates an instance of the + class + \end{itemize} +\footnotesize +\begin{lstlisting} +class Foo(object): + pass +# class object created. +# Create an instance of Foo. +f = Foo() +# Can assign an attribute to the instance +f.a = 100 +print f.a +100 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes \ldots} + \begin{itemize} + \item All attributes are accessed via the \typ{object.attribute} + syntax + \item Both class and instance attributes are supported + \item \emph{Methods} represent the behavior of an object: crudely + think of them as functions ``belonging'' to the object + \item All methods in Python are ``virtual'' + \item Inheritance through subclassing + \item Multiple inheritance is supported + \item No special public and private attributes: only good + conventions + \begin{itemize} + \item \verb+object.public()+: public + \item \verb+object._private()+ \& \verb+object.__priv()+: + non-public + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: examples} +\begin{lstlisting} +class MyClass(object): + """Example class (this is the class docstring).""" + i = 12345 # A class attribute + def f(self): + """This is the method docstring""" + return 'hello world' + +>>> a = MyClass() # creates an instance +>>> a.f() +'hello world' +>>> # a.f() is equivalent to MyClass.f(a) +... # This also explains why f has a 'self' argument. +... MyClass.f(a) +'hello world' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes (continued)} + \begin{itemize} + \item \typ{self} is \alert{conventionally} the first argument for a + method + \item In previous example, \typ{a.f} is a method object + \item When \typ{a.f} is called, it is passed the instance \typ{a} as + the first argument + \item If a method called \verb+__init__+ exists, it is called when + the object is created + \item If a method called \verb+__del__+ exists, it is called before + the object is garbage collected + \item Instance attributes are set by simply ``setting'' them in + \typ{self} + \item Other special methods (by convention) like \verb+__add__+ let + you define numeric types: + {\footnotesize \url{http://docs.python.org/ref/specialnames.html} + \\ \url{http://docs.python.org/ref/numeric-types.html} + } + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: examples} +\begin{lstlisting} +class Bag(MyClass): # Shows how to derive classes + def __init__(self): # called on object creation. + self.data = [] # an instance attribute + def add(self, x): + self.data.append(x) + def addtwice(self, x): + self.add(x) + self.add(x) +>>> a = Bag() +>>> a.f() # Inherited method +'hello world' +>>> a.add(1); a.addtwice(2) +>>> a.data +[1, 2, 2] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Derived classes} + \begin{itemize} + \item Call the parent's \verb+__init__+ if needed + \item If you don't need a new constructor, no need to define it in subclass + \item Can also use the \verb+super+ built-in function + \end{itemize} +\begin{lstlisting} +class AnotherBag(Bag): + def __init__(self): + # Must call parent's __init__ explicitly + Bag.__init__(self) + # Alternatively use this: + super(AnotherBag, self).__init__() + # Now setup any more data. + self.more_data = [] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: polymorphism} +\begin{lstlisting} +class Drawable(object): + def draw(self): + # Just a specification. + pass +\end{lstlisting} +\mode<presentation>{\pause} +\begin{lstlisting} +class Square(Drawable): + def draw(self): + # draw a square. +class Circle(Drawable): + def draw(self): + # draw a circle. +\end{lstlisting} +\mode<presentation>{\pause} +\begin{lstlisting} +class Artist(Drawable): + def draw(self): + for obj in self.drawables: + obj.draw() +\end{lstlisting} +\end{frame} + +\subsection{Miscellaneous} + +\begin{frame}[fragile] + \frametitle{Stand-alone scripts} +Consider a file \typ{f.py}: +\begin{lstlisting} +#!/usr/bin/env python +"""Module level documentation.""" +# First line tells the shell that it should use Python +# to interpret the code in the file. +def f(): + print "f" + +# Check if we are running standalone or as module. +# When imported, __name__ will not be '__main__' +if __name__ == '__main__': + # This is not executed when f.py is imported. + f() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List comprehensions} +\begin{lstlisting} +>>> veg = ['tomato', 'cabbage', 'carrot', 'potato'] +>>> [x.upper() for x in veg] +['TOMATO', 'CABBAGE', 'CARROT', 'POTATO'] +>>> vec = range(0, 8) +>>> even = [x for x in vec if x%2 == 0] +>>> even +[0, 2, 4, 6] +>>> [x*x for x in even] +[0, 4, 16, 36] +>>> odd = [x for x in vec if x%2 == 1] +>>> odd +[1, 3, 5, 7] +>>> [x*y for x in even for y in odd] +[0, 0, 0, 0, 2, 6, 10, 14, 4, 12, 20, 28, 6, 18,30,42] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features} + \begin{itemize} + \item Input and output caching: + \begin{itemize} + \item \verb+In+: a list of all entered input + \item \verb+Out+: a dict of all output + \item \verb+_+, \verb+__+, \verb+__+ are the last three results as + is \verb+_N+ + \item \verb+%hist [-n]+ macro shows previous history, \verb+-n+ + suppresses line number information + \end{itemize} + \item Log the session using \verb+%logstart+, \verb+%logon+ and + \verb+%logoff+ + \item \verb+%run [options] file[.py]+ -- running Python code + \begin{itemize} + \item \verb+%run -d [-b<N>]+: debug script with pdb + \verb+N+ is the line number to break at (defaults to 1) + \item \verb+%run -t+: time the script + \item \verb+%run -p+: Profile the script + \end{itemize} + \item \verb+%prun+ runs a statement/expression under the profiler + \item \verb+%macro [options] macro_name n1-n2 n3-n4 n6+ save specified + lines to a macro with name \verb+macro_name+ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features \ldots} + \begin{itemize} + \item \verb+%edit [options] [args]+: edit lines of code or file + specified in editor (configure editor via \verb+$EDITOR+) + \item \verb+%cd+ changes directory, see also \verb+%pushd, %popd, %dhist+ + \item Shell access + \begin{itemize} + \item \verb+!command+ runs a shell command and returns its output + \item \verb+files = %sx ls+ or \verb+files = !ls+ sets + \verb+files+ to all result of the \verb+ls+ command + \item \verb+%sx+ is quiet + \item \verb+!ls $files+ passes the \verb+files+ variable to the + shell command + \item \verb+%alias alias_name cmd+ creates an alias for a system + command + \end{itemize} + \item \verb+%colors+ lets you change the color scheme to + \verb+NoColor, Linux, LightBG+ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features \ldots} + \begin{itemize} + \item Use \verb+;+ at the end of a statement to suppress printing + output + \item \verb+%bookmark+: store a bookmarked location, for use with \verb+%cd+ + \item \verb+%who, %whos+: print information on variables + \item \verb+%save [options] filename n1-n2 n3-n4+: save lines to a + file + \item \verb+%time statement+: Time execution of a Python statement or + expression + \item \verb+%timeit [-n<N> -r<R> [-t|-c]] statement+: time execution + using Python's timeit module + \item Can define and use profiles to setup IPython differently: + \verb+math, scipy, numeric, pysh+ etc. + \item \verb+%magic+: \alert{Show help on all magics} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File handling} +\begin{lstlisting} +>>> # Reading files: +... f = open('/path/to/file_name') +>>> data = f.read() # Read entire file. +>>> line = f.readline() # Read one line. +>>> # Read entire file appending each line into a list +... lines = f.readlines() +>>> f.close() # close the file. +>>> # Writing files: +... f = open('/path/to/file_name', 'w') +>>> f.write('hello world\n') +\end{lstlisting} + \begin{itemize} + \item \typ{tell()}: returns int of current position + \item \typ{seek(pos)}: moves current position to specified byte + \item Call \typ{close()} when done using a file + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Math} + \begin{itemize} + \item \typ{math} module provides basic math routines for + floats + \item \typ{cmath} module provides math routies for complex + numbers + \item \typ{random}: provides pseudo-random number generators + for various distributions + \item These are always available and part of the standard library + \item More serious math is provided by the NumPy/SciPy modules -- + these are not standard and need to be installed separately + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Timing and profiling} + \begin{itemize} + \item Timing code: use the \typ{time} module + \item Read up on \typ{time.time()} and \typ{time.clock()} + \item \typ{timeit}: is a better way of doing timing + \item IPython has handy \typ{time} and \typ{timeit} macros (type + \typ{timeit?} for help) + \item IPython lets you debug and profile code via the \typ{run} + macro (type \typ{run?} on the prompt to learn more) + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item \typ{dir([object])} function: attributes of given object + \item \typ{type(object)}: returns type information + \item \typ{str(), repr()}: convert object to string representation + \item \typ{isinstance, issubclass} + \item \typ{assert} statements let you do debugging assertions in + code + \item \typ{csv} module: reading and writing CSV files + \item \typ{pickle}: lets you save and load Python objects + (\alert{serialization}) + \item \typ{sys.argv}: command line arguments + \item \typ{os.path}: common path manipulations + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Test driven development (TDD)} + \begin{itemize} + \item Why? + \begin{itemize} + + \item Forces you to write reusable code! + + \item Think about the API + + \item More robust + + \item Makes refactoring very easy + + \end{itemize} + \item How? Python offers three major ways of doing this + \begin{itemize} + \item doctest + \item unittest + \item nosetest (and similar like py.test) + \end{itemize} + + \item Test every piece of functionality you offer + + \item This isn't a formal introduction but more a practical one + + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Unit test} +\begin{lstlisting} +import unittest + +class MyTestCase(unittest.TestCase): + def setUp(self): + # Called *before* each test_* + def tearDown(self): + # Called *after* each test_* + def test_something(self): + "docstring" + # Test code. + self.assertEqual(x, y) + self.assertRaises(ValueError, func, arg1, arg2 ...) + +if __name__ == '__main__': + unittest.main() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Nosetest} +\begin{lstlisting} +import particle +def test_particle(): + # Use asserts here. + p = particle.Particle(1.0) + assert p.property[0] == 1.0 + assert p.property[2] == 0.0 + +if __name__ == '__main__': + import nose + nose.main() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Testing} + \begin{itemize} + \item More details: see library reference and search for nosetest + \end{itemize} +\end{frame} + +\section{Numerics \& Plotting} + +\subsection{NumPy Arrays} + +\newcommand{\num}{\texttt{numpy}} + +\begin{frame} + \frametitle{The \num\ module} + \begin{itemize} + \item Manipulating large Python lists for scientific computing is + \alert{slow} + \item Most complex computations can be reduced to a few standard + operations + \item The \num\ module provides: + \begin{itemize} + \item An efficient and powerful array type for various common data + types + \item Abstracts out the most commonly used standard operations on + arrays + \end{itemize} + \item Numeric was the first, then came \texttt{numarray}. + \texttt{numpy} is the latest and is the future + \item This course uses \num\ and only covers the absolute basics + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Basic concepts} + \begin{itemize} + \item \num\ arrays are of a fixed size (\typ{arr.size}) and have the + same type (\typ{arr.dtype}) + \item \num\ arrays may have arbitrary dimensionality + \item The \typ{shape} of an array is the extent (length) of the + array along each dimension + \item The \typ{rank(arr)} of an array is the ``dimensionality'' of the + array + \item The \typ{arr.itemsize} is the number of bytes (8-bits) used for + each element of the array + \item \alert{Note:} The \typ{shape} and \typ{rank} may change as + long as the \typ{size} of the array is fixed + \item \alert{Note:} \typ{len(arr) != arr.size} in general + \item \alert{Note:} By default array operations are performed + \alert{elementwise} + \item Indices start from 0 + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Examples of \num} +\begin{lstlisting} +# Simple array math example +>>> from numpy import * +>>> a = array([1,2,3,4]) +>>> b = array([2,3,4,5]) +>>> a + b # Element wise addition! +array([3, 5, 7, 9]) + +>>> print pi, e # Pi and e are defined. +3.14159265359 2.71828182846 +# Create array from 0 to 10 +>>> x = arange(0.0, 10.0, 0.05) +>>> x *= 2*pi/10 # multiply array by scalar value +array([ 0.,0.0314,...,6.252]) +# apply functions to array. +>>> y = sin(x) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More examples of \num} +\vspace*{-8pt} +\begin{lstlisting} +# Size, shape, rank, type etc. +>>> x = array([1., 2, 3, 4]) +>>> size(x) +4 +>>> x.dtype # or x.dtype.char +'d' +>>> x.shape +(4,) +>>> print rank(x), x.itemsize +1 8 +>>> x.tolist() +[1.0, 2.0, 3.0, 4.0] +# Array indexing +>>> x[0] = 10 +>>> print x[0], x[-1] +10.0 4.0 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Multi-dimensional arrays} +\begin{lstlisting} +>>> a = array([[ 0, 1, 2, 3], +... [10,11,12,13]]) +>>> a.shape # (rows, columns) +(2, 4) +# Accessing and setting values +>>> a[1,3] +13 +>>> a[1,3] = -1 +>>> a[1] # The second row +array([10,11,12,-1]) + +# Flatten/ravel arrays to 1D arrays +>>> a.flat # or ravel(a) +array([0,1,2,3,10,11,12,-1]) +# Note: flat references original memory +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Slicing arrays} +\begin{lstlisting} +>>> a = array([[1,2,3], [4,5,6], [7,8,9]]) +>>> a[0,1:3] +array([2, 3]) +>>> a[1:,1:] +array([[5, 6], + [8, 9]]) +>>> a[:,2] +array([3, 6, 9]) +# Striding... +>>> a[0::2,0::2] +array([[1, 3], + [7, 9]]) +# All these slices are references to the same memory! +\end{lstlisting} +\end{frame} + +% \begin{frame}[fragile] +% \frametitle{Array types and typecodes} +% \begin{tabular}[c]{|c|c|p{2.75in}|} +% \hline +% Character & Bits (bytes) & Type name \\ +% \hline +% D & 128 (16) & \typ{Complex, Complex64}\\ +% F & 64 (8) & \typ{Complex0, Complex8, Complex16} \\ +% d & 64 (8) & \typ{Float, Float64} \\ +% f & 32 (4) & \typ{Float0, Float8, Float16} \\ +% i & 32 (4) & \typ{Int32} \\ +% l & 32 (4) & \typ{Int} \\ +% O & 4 (1) & \typ{PyObject} \\ +% %b 8 (1) UnsignedInt8 +% %1 (one) 8 (1) Int8 +% %s 16 (2) Int16 +% \hline +% \end{tabular} +% \begin{lstlisting} +% # Examples +% >>> f = array([1,2,3], Float32) +% >>> c = array([1,2,3], Complex32) +% >>> print f, c +% [ 1. 2. 3.] [ 1.+0.j 2.+0.j 3.+0.j] +% \end{lstlisting} +% \end{frame} + +\begin{frame}[fragile] + \frametitle{Array creation functions} + \begin{itemize} + \item \typ{array(object, dtype=None, copy=1,order=None, subok=0,ndmin=0)} + \item \typ{arange(start, stop=None, step=1, dtype=None)} + \item \typ{linspace(start, stop, num=50, endpoint=True, retstep=False)} + \item \typ{ones(shape, dtype=None, order='C')} + \item \typ{zeros((d1,...,dn),dtype=float,order='C')} + \item \typ{identity(n)} + \item \typ{empty((d1,...,dn),dtype=float,order='C')} + \item \typ{ones\_like(x)}, \typ{zeros\_like(x)}, \typ{empty\_like(x)} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Array math} + \begin{itemize} + \item Basic \alert{elementwise} math (given two arrays \typ{a, b}): + \begin{itemize} + \item \typ{a + b $\rightarrow$ add(a, b)} + \item \typ{a - b, $\rightarrow$ subtract(a, b)} + \item \typ{a * b, $\rightarrow$ multiply(a, b)} + \item \typ{a / b, $\rightarrow$ divide(a, b)} + \item \typ{a \% b, $\rightarrow$ remainder(a, b)} + \item \typ{a ** b, $\rightarrow$ power(a, b)} + \end{itemize} + \item Inplace operators: \typ{a += b}, or \typ{add(a, b, + a)} etc. + \item Logical operations: \typ{equal (==)}, \typ{not\_equal (!=)}, + \typ{less (<)}, \typ{greater (>)} etc. + \item Trig and other functions: \typ{sin(x), arcsin(x), sinh(x), + exp(x), sqrt(x)} etc. + \item \typ{sum(x, axis=0), product(x, axis=0)}: sum and product of array elements + \item \typ{dot(a, b)} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Advanced} + \begin{itemize} + \item Only scratched the surface of \num + \item Ufunc methods: \typ{reduce, accumulate, outer, reduceat} + \item Typecasting + \item More functions: \typ{take, choose, where, compress, + concatenate} + \item Array broadcasting and \typ{None} + \end{itemize} +\end{frame} + +\subsection{Plotting: Matplotlib} + +\begin{frame} + \frametitle{About \texttt{matplotlib}} + \begin{itemize} + \item Easy to use, scriptable, ``Matlab-like'' 2D plotting + \item Publication quality figures and interactive capabilities + \item Plots, histograms, power spectra, bar charts, errorcharts, + scatterplots, etc. + \item Also does polar plots, maps, contours + \item Support for simple \TeX\ markup + \item Multiple output backends (images, EPS, SVG, wx, Agg, Tk, GTK) + \item Cross-platform: Linux, Win32, Mac OS X + \item Good idea to use via IPython: \typ{ipython -pylab} + \item From scripts use: \typ{import pylab} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{More information} + \begin{itemize} + \item More information here: \url{http://matplotlib.sf.net} + \item \url{http://matplotlib.sf.net/tutorial.html} + \item \url{http://matplotlib.sf.net/screenshots.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting with \texttt{matplotlib}} +\begin{lstlisting} +>>> x = arange(0, 2*pi, 0.05) +>>> plot(x, sin(x)) # Same as plot(x, sin(x), 'b-') +>>> plot(x, sin(x), 'ro') +>>> axis([0,2*pi, -1,1]) +>>> xlabel(r'$\chi$', color='g') +>>> ylabel(r'sin($\chi$)', color='r') +>>> title('A simple figure', fontsize=20) +>>> savefig('/tmp/test.eps') +# Multiple plots in one figure +>>> t = arange(0.0, 5.2, 0.2) +# red dashes, blue squares and green triangles +>>> plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting \ldots} +\begin{lstlisting} +# Set properties of objects: +>>> plot(x, sin(x), linewidth=2.0, color='r') +>>> l, = plot(x, sin(x)) +>>> setp(l, linewidth=2.0, color='r') +>>> l.set_linewidth(2.0); l.set_color('r') +>>> draw() # Redraws current figure. +>>> setp(l) # Prints available properties +>>> close() # Closes the figure. +# Multiple figures: +>>> figure(1); plot(x, sin(x)) +>>> figure(2); plot(x, tanh(x)) +>>> figure(1); title('Easy as 1,2,3') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting \ldots} +\begin{lstlisting} +>>> figure(1) +>>> subplot(211) # Same as subplot(2, 1, 1) +>>> plot(x, cos(5*x)*exp(-x)) +>>> subplot(2, 1, 2) +>>> plot(x, cos(5*x), 'r--', label='cosine') +>>> plot(x, sin(5*x), 'g--', label='sine') +>>> legend() # Or legend(['cosine', 'sine']) +>>> text(1,0, '(1,0)') +>>> axes = gca() # Current axis +>>> fig = gcf() # Current figure +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{X-Y plot} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/xyplot} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +t1 = arange(0.0, 5.0, 0.1) +t2 = arange(0.0, 5.0, 0.02) +t3 = arange(0.0, 2.0, 0.01) +subplot(211) +plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', + t2, cos(2*pi*t2)*exp(-t2), 'k') +grid(True) +title('A tale of 2 subplots') +ylabel('Damped') +subplot(212) +plot(t3, cos(2*pi*t3), 'r--') +grid(True) +xlabel('time (s)') +ylabel('Undamped') +\end{lstlisting} + \end{block} + \end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Errorbar} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/errorbar} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +t = arange(0.1, 4, 0.1) +s = exp(-t) +e = 0.1*abs(randn(len(s))) +f = 0.1*abs(randn(len(s))) +g = 2*e +h = 2*f +errorbar(t, s, [e,g], f, fmt='o') +xlabel('Distance (m)') +ylabel('Height (m)') +title('Mean and standard error '\ + 'as a function of distance') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Semi-log and log-log plots} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/log} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +dt = 0.01 +t = arange(dt, 20.0, dt) +subplot(311) +semilogy(t, exp(-t/5.0)) +ylabel('semilogy') +grid(True) +subplot(312) +semilogx(t, sin(2*pi*t)) +ylabel('semilogx') +grid(True) +# minor grid on too +gca().xaxis.grid(True, which='minor') +subplot(313) +loglog(t, 20*exp(-t/10.0), basex=4) +grid(True) +ylabel('loglog base 4 on x') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Histogram} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/histogram} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +mu, sigma = 100, 15 +x = mu + sigma*randn(10000) +# the histogram of the data +n, bins, patches = hist(x, 100, normed=1) +# add a 'best fit' line +y = normpdf( bins, mu, sigma) +l = plot(bins, y, 'r--', linewidth=2) +xlim(40, 160) +xlabel('Smarts') +ylabel('P') +title(r'$\rm{IQ:}\/ \mu=100,\/ \sigma=15$') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Bar charts} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/barchart} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +N = 5 +menMeans = (20, 35, 30, 35, 27) +menStd = ( 2, 3, 4, 1, 2) +# the x locations for the groups +ind = arange(N) +# the width of the bars +width = 0.35 +p1 = bar(ind, menMeans, width, + color='r', yerr=menStd) +womenMeans = (25, 32, 34, 20, 25) +womenStd = ( 3, 5, 2, 3, 3) +p2 = bar(ind+width, womenMeans, width, + color='y', yerr=womenStd) +ylabel('Scores') +title('Scores by group and gender') +xticks(ind+width, + ('G1', 'G2', 'G3', 'G4', 'G5')) +xlim(-width,len(ind)) +yticks(arange(0,41,10)) +legend((p1[0], p2[0]), + ('Men', 'Women'), shadow=True) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Pie charts} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.4in} + \includegraphics[height=2.0in, interpolate=true]{data/piechart} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +# make a square figure and axes +figure(1, figsize=(8,8)) +ax = axes([0.1, 0.1, 0.8, 0.8]) +labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' +fracs = [15,30,45, 10] +explode=(0, 0.05, 0, 0) +pie(fracs, explode=explode, labels=labels, + autopct='%1.1f%%', shadow=True) +title('Raining Hogs and Dogs', + bbox={'facecolor':'0.8', 'pad':5}) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Scatter plots} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.4in} + \includegraphics[height=2in, interpolate=true]{data/scatter} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +N = 30 +x = 0.9*rand(N) +y = 0.9*rand(N) +# 0 to 10 point radiuses +area = pi*(10 * rand(N))**2 +volume = 400 + rand(N)*450 +scatter(x,y,s=area, marker='o', c=volume, + alpha=0.75) +xlabel(r'$\Delta_i$', size='x-large') +ylabel(r'$\Delta_{i+1}$', size='x-large') +title(r'Volume and percent change') +grid(True) +colorbar() +savefig('scatter') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Polar} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/polar} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +figure(figsize=(8,8)) +ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, + axisbg='#d5de9c') +r = arange(0,1,0.001) +theta = 2*2*pi*r +polar(theta, r, color='#ee8d18', lw=3) +# the radius of the grid labels +setp(ax.thetagridlabels, y=1.075) +title(r"$\theta=4\pi r", fontsize=20) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Contours} + \begin{columns} + \column{0.45\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/contour} + \column{0.525\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +x = arange(-3.0, 3.0, 0.025) +y = arange(-2.0, 2.0, 0.025) +X, Y = meshgrid(x, y) +Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) +# difference of Gaussians +Z = 10.0 * (Z2 - Z1) +im = imshow(Z, interpolation='bilinear', + origin='lower', + cmap=cm.gray, extent=(-3,3,-2,2)) +levels = arange(-1.2, 1.6, 0.2) +# label every second level +clabel(CS, levels[1::2], inline=1, + fmt='%1.1f', fontsize=14) +CS = contour(Z, levels, + origin='lower', + linewidths=2, + extent=(-3,3,-2,2)) +# make a colorbar for the contour lines +CB = colorbar(CS, shrink=0.8, extend='both') +title('Lines with colorbar') +hot(); flag() +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Velocity vectors} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/quiver} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +X,Y = meshgrid(arange(0,2*pi,.2), + arange(0,2*pi,.2) ) +U = cos(X) +V = sin(Y) +Q = quiver(X[::3, ::3], Y[::3, ::3], + U[::3, ::3], V[::3, ::3], + color='r', units='x', + linewidths=(2,), + edgecolors=('k'), + headaxislength=5 ) +qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', + fontproperties= + {'weight': 'bold'}) +axis([-1, 7, -1, 7]) +title('triangular head; scale '\ + 'with x view; black edges') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Maps} + \includegraphics[height=2.5in, interpolate=true]{data/plotmap} + \begin{center} + \tiny + For details see \url{http://matplotlib.sourceforge.net/screenshots/plotmap.py} + \end{center} +\end{frame} + + +\subsection{SciPy} + +\begin{frame} + \frametitle{Using \texttt{SciPy}} + \begin{itemize} + \item SciPy is Open Source software for mathematics, science, and + engineering + \item \typ{import scipy} + \item Built on NumPy + \item Provides modules for statistics, optimization, integration, + linear algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + \item Used widely by scientists world over + \item Details are beyond the scope of this tutorial + \end{itemize} +\end{frame} + +\section{Standard library} + +\subsection{Quick Tour} + +\begin{frame} + \frametitle{Standard library} + \begin{itemize} + \item Very powerful + \item ``Batteries included'' + \item Example standard modules taken from the tutorial + \begin{itemize} + \item Operating system interface: \typ{os} + \item System, Command line arguments: \typ{sys} + \item Regular expressions: \typ{re} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib2}, \typ{smtplib} + \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, + \typ{zipfile}, and \typ{tarfile} + \item Unit testing: \typ{doctest} and \typ{unittest} + \item And a whole lot more! + \end{itemize} + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import os +>>> os.system('date') +Fri Jun 10 22:13:09 IST 2005 +0 +>>> os.getcwd() +'/home/prabhu' +>>> os.chdir('/tmp') +>>> import os +>>> dir(os) +<returns a list of all module functions> +>>> help(os) +<extensive manual page from module's docstrings> +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import sys +>>> # Print the list of command line args to Python +... print sys.argv +[''] +>>> import re # Regular expressions +>>> re.findall(r'\bf[a-z]*', +... 'which foot or hand fell fastest') +['foot', 'fell', 'fastest'] +>>> re.sub(r'(\b[a-z]+) \1', r'\1', +... 'cat in the the hat') +'cat in the hat' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import math +>>> math.cos(math.pi / 4.0) +0.70710678118654757 +>>> math.log(1024, 2) +10.0 +>>> import random +>>> random.choice(['apple', 'pear', 'banana']) +'pear' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import urllib2 +>>> f = urllib2.urlopen('http://www.python.org/') +>>> print f.read(100) +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<?xml-stylesheet href="./css/ht2html +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import zlib +>>> s = 'witch which has which witches wrist watch' +>>> len(s) +41 +>>> t = zlib.compress(s) +>>> len(t) +37 +>>> zlib.decompress(t) +'witch which has which witches wrist watch' +>>> zlib.crc32(t) +-1438085031 +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Introduced Python + \item Basic syntax + \item Basic types and data structures + \item Control flow + \item Functions + \item Modules + \item Exceptions + \item Classes + \item Standard library + \end{itemize} +\end{frame} + +\end{document} + +\subsection{Basic data structures} +\begin{frame}{Lists} + \begin{itemize} + \item \texttt{species = [ 'humans', 'orcs', 'elves', 'dwarves' ]} + \item \texttt{ ids = [ 107, 109, 124, 141, 142, 144 ]} + \item \texttt{ oneliners = [ 'I will be back', 'Do or do not! No try!!', 42 ] } + \end{itemize} + + \begin{block}{List operations} + ids + [ 100, 102 ]\\ + species.append( 'unicorns')\\ + print oneliners[ 1 ]\\ + look up \alert{docs.python.org/tutorial/datastructures.html} + \end{block} +\end{frame} +\end{document} +\section{Python Tutorial} +\subsection{Preliminaries} +\begin{frame} + \frametitle{Using the interpreter} + \begin{itemize} + \item Starting up: \typ{python} or \typ{ipython} + \item Quitting: \typ{Control-D} or \typ{Control-Z} (on Win32) + \item Can use it like a calculator + \item Can execute one-liners via the \typ{-c} option: + \typ{python -c "print 'hello world'"} + \item Other options via \typ{python -h} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{IPython} + \begin{itemize} + \item Recommended interpreter, IPython: + \url{http://ipython.scipy.org} + \item Better than the default Python shell + \item Supports tab completion by default + \item Easier object introspection + \item Shell access! + \item Command system to allow extending its own behavior + \item Supports history (across sessions) and logging + \item Can be embedded in your own Python code + \item Support for macros + \item A flexible framework for your own custom interpreter + \item Other miscellaneous conveniences + \item We'll get back to this later + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic IPython features} + \begin{itemize} + \item Startup: \verb+ipython [options] files+ + \begin{itemize} + \item \verb+ipython [-wthread|-gthread|-qthread]+: + Threading modes to support wxPython, pyGTK and Qt + \item \verb+ipython -pylab+: Support for matplotlib + \end{itemize} + \item TAB completion: + \begin{itemize} + \item Type \verb+object_name.<TAB>+ to see list of options + \item Also completes on file and directory names + \end{itemize} + \item \verb+object?+ shows docstring/help for any Python object + \item \verb+object??+ presents more docs (and source if possible) + \item Debugging with \verb+%pdb+ magic: pops up pdb on errors + \item Access history (saved over earlier sessions also) + \begin{itemize} + \item Use \texttt{<UpArrow>}: move up history + \item Use \texttt{<Ctrl-r> string}: search history backwards + \item Use \texttt{Esc >}: get back to end of history + \end{itemize} + \item \verb+%run [options] file[.py]+ lets you run Python code + \end{itemize} +\end{frame} +% LocalWords: BDFL Guido Rossum PSF Nokia OO Zope CMS RedHat SciPy MayaVi spam +% LocalWords: IPython ipython stdin TypeError dict int elif PYTHONPATH IOError +% LocalWords: namespace Namespaces SyntaxError ZeroDivisionError NameError str +% LocalWords: ValueError subclassed def + + + \item Types are of two kinds: \alert{mutable} and \alert{immutable} + \item Immutable types: numbers, strings, \typ{None} and tuples + \item Immutables cannot be changed ``in-place'' + \item Mutable types: lists, dictionaries, instances, etc. + \item Mutable objects can be ``changed'' + \end{itemize} + + +\begin{frame} + \frametitle{Important!} + \begin{itemize} + \item Assignment to an object is by reference + \item Essentially, \alert{names are bound to objects} + \end{itemize} +\end{frame} + + +\end{document} +\begin{frame}[fragile] + \frametitle{Dictionaries} + \begin{itemize} + \item Associative arrays/mappings + \item Indexed by ``keys'' (keys must be immutable) + \item \typ{dict[key] = value} + \item \typ{keys()} returns all keys of the dict + \item \typ{values()} returns the values of the dict + \item \verb+has_key(key)+ returns if \typ{key} is in the dict + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries: example} + \begin{lstlisting} +>>> tel = {'jack': 4098, 'sape': 4139} +>>> tel['guido'] = 4127 +>>> tel +{'sape': 4139, 'guido': 4127, 'jack': 4098} +>>> tel['jack'] +4098 +>>> del tel['sape'] +>>> tel['irv'] = 4127 +>>> tel +{'guido': 4127, 'irv': 4127, 'jack': 4098} +>>> tel.keys() +['guido', 'irv', 'jack'] +>>> tel.has_key('guido') +True + \end{lstlisting} +\end{frame} + +\subsection{Control flow, functions} + + + +\begin{frame}[fragile] + \frametitle{\typ{If} example} + \begin{lstlisting} +>>> a = ['cat', 'window', 'defenestrate'] +>>> if 'cat' in a: +... print "meaw" +... +meaw +>>> pets = {'cat': 1, 'dog':2, 'croc': 10} +>>> if 'croc' in pets: +... print pets['croc'] +... +10 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for} example} + \begin{lstlisting} +>>> a = ['cat', 'window', 'defenestrate'] +>>> for x in a: +... print x, len(x) +... +cat 3 +window 6 +defenestrate 12 +>>> knights = {'gallahad': 'the pure', +... 'robin': 'the brave'} +>>> for k, v in knights.iteritems(): +... print k, v +... +gallahad the pure +robin the brave +\end{lstlisting} +\end{frame} diff --git a/day1/Session-1.toc b/day1/Session-1.toc new file mode 100644 index 0000000..165b519 --- /dev/null +++ b/day1/Session-1.toc @@ -0,0 +1,13 @@ +\beamer@endinputifotherversion {3.07pt} +\select@language {english} +\beamer@sectionintoc {1}{Agenda}{4}{0}{1} +\beamer@sectionintoc {2}{Agenda}{5}{0}{2} +\beamer@sectionintoc {3}{Overview}{7}{0}{3} +\beamer@sectionintoc {4}{Python}{13}{0}{4} +\beamer@subsectionintoc {4}{1}{Getting Started}{13}{0}{4} +\beamer@subsectionintoc {4}{2}{Data types}{22}{0}{4} +\beamer@subsectionintoc {4}{3}{Control flow}{35}{0}{4} +\beamer@subsectionintoc {4}{4}{Functions}{48}{0}{4} +\beamer@subsectionintoc {4}{5}{Lists}{62}{0}{4} +\beamer@subsectionintoc {4}{6}{IO}{82}{0}{4} +\beamer@subsectionintoc {4}{7}{Modules}{89}{0}{4} diff --git a/day1/Session-1.vrb b/day1/Session-1.vrb new file mode 100644 index 0000000..24c7600 --- /dev/null +++ b/day1/Session-1.vrb @@ -0,0 +1,6 @@ +\frametitle {Problem 5.1} + + Put all the functions you have written so far as part of the problems + into one module called \typ{iitb.py} and use this module from IPython. + +\inctime{20} diff --git a/day1/Session-2.tex b/day1/Session-2.tex new file mode 100755 index 0000000..0e0fd96 --- /dev/null +++ b/day1/Session-2.tex @@ -0,0 +1,2745 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Tutorial slides on Python. +% +% Author: Prabhu Ramachandran <prabhu at aero.iitb.ac.in> +% Copyright (c) 2005-2008, Prabhu Ramachandran +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} +%\documentclass[draft]{beamer} +%\documentclass[compress,handout]{beamer} +%\usepackage{pgfpages} +%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] + +% Modified from: generic-ornate-15min-45min.de.tex +\mode<presentation> +{ + \usetheme{Warsaw} + \useoutertheme{split} + \setbeamercovered{transparent} +} + +\usepackage[english]{babel} +\usepackage[latin1]{inputenc} +%\usepackage{times} +\usepackage[T1]{fontenc} + +% Taken from Fernando's slides. +\usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} +\usepackage[scaled=.95]{helvet} + +\definecolor{darkgreen}{rgb}{0,0.5,0} + +\usepackage{listings} +\lstset{language=Python, + basicstyle=\ttfamily, + commentstyle=\color{red}\itshape, + stringstyle=\color{darkgreen}, + showstringspaces=false, + keywordstyle=\color{blue}\bfseries} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Macros +\setbeamercolor{emphbar}{bg=blue!20, fg=black} +\newcommand{\emphbar}[1] +{\begin{beamercolorbox}[rounded=true]{emphbar} + {#1} + \end{beamercolorbox} +} +\newcounter{time} +\setcounter{time}{0} +\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} + +\newcommand{\typ}[1]{\texttt{#1}} + +\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } + +%%% This is from Fernando's setup. +% \usepackage{color} +% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} +% % Use and configure listings package for nicely formatted code +% \usepackage{listings} +% \lstset{ +% language=Python, +% basicstyle=\small\ttfamily, +% commentstyle=\ttfamily\color{blue}, +% stringstyle=\ttfamily\color{orange}, +% showstringspaces=false, +% breaklines=true, +% postbreak = \space\dots +% } + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Basic Python]{Python:\\A great programming toolkit} + +\author[Asokan \& Prabhu] {Asokan Pichai\\Prabhu Ramachandran} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {25, July 2009} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} +%\logo{\pgfuseimage{iitmlogo}} + + +%% Delete this, if you do not want the table of contents to pop up at +%% the beginning of each subsection: +\AtBeginSubsection[] +{ + \begin{frame}<beamer> + \frametitle{Outline} + \tableofcontents[currentsection,currentsubsection] + \end{frame} +} + + +% If you wish to uncover everything in a step-wise fashion, uncomment +% the following command: +%\beamerdefaultoverlayspecification{<+->} + +%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% DOCUMENT STARTS +\begin{document} + +\begin{frame} + \titlepage +\end{frame} +\begin{frame} + {Acknowledgements} + \begin{center} + This program is conducted by\\ + IIT, Bombay\\ + through CDEEP\\as part of the open source initiatives\\ + under the aegis of\\ + \alert{National Mission on Education through ICT,} \\ + Ministry of HRD. + \end{center} +\end{frame} + +\begin{frame} + \frametitle{Outline} + \tableofcontents + % You might wish to add the option [pausesections] +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TODO +% +% * Add slide on Python packages (modules) +% * Add slides on reference counting. + +\section{Agenda} +\begin{frame}{About the Workshop} + \begin{description} + \item[Session 1] Sat 14:00--15:55 + \item[Session 2] Sat 16:05--18:00 + \item[Session 3] Sun 14:00--15:55 + \item[Session 4] Sun 16:05--18:00 + \end{description} + + \begin{block}{Goal of the workshop} + At the end of this program, successful participants will be able to use python as their scripting and problem solving language. Aimed at Engg. students--focus on basic numerics and plotting-- but should serve a similar purpose for others. + \end{block} +\end{frame} + +\begin{frame}{Checklist} + Let us verify that all of us are having the same (similar) tools and environment + \begin{description} + \item[python] Type python at the command line. Do you see version 2.5 or later? + \item[IPython] Is IPython available? + \item[Editor] Which editor? scite, vim, emacs, \ldots + \end{description} +\end{frame} + +\section{Overview} +\begin{frame}{Session 1} + \begin{itemize} + \item Introduction and motivation + \item Using the interpreter(s) + \item Basic data types: int, float, string + \item Basic data structures: list + \item Basic console IO: \texttt{raw\_input(), print} + \item Basic control flow: \texttt{if, while} + \item Problem set 1 + \item Functions $\rightarrow$ Problem set 2 + \item lists, \texttt{for} $\rightarrow$ Problem set 3 + \item IO, Modules $\rightarrow$ Problem sets 4,5, \ldots + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Introduction} + \begin{itemize} + \item Creator and BDFL: Guido van Rossum + \item Conceived in December 1989 + \item ``Python'' as in Monty Python's Flying Circus + \item Current stable version of Python is 2.6.x + \item PSF license (like BSD: no strings attached) + \item Highly cross platform + \item Runs on the Nokia series 60! + \item \alert{Philosophy:} Simple and complete by design + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Resources} + \begin{itemize} + \item Part of many GNU/Linux distributions + \item Web: \url{http://www.python.org} + \item Doc: \url{http://www.python.org/doc} + \item Free Tutorials: + \begin{itemize} + \item Official Python tutorial: \url{http://docs.python.org/tut/tut.html} + \item Byte of Python: \url{http://www.byteofpython.info/} + \item Dive into Python: \url{http://diveintopython.org/} + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Why Python?} + \begin{itemize} + \item Designed to be readable and easy to use + \item High level, interpreted, modular, OO + \item Much faster development cycle + \item Powerful interactive environment + \item Rapid application development + \item Rich standard library and modules + \item Interfaces well with C++, C and FORTRAN + \item \alert{More than a math package $\Rightarrow$ some extra work compared to math packages} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Use cases} + \begin{itemize} + \item NASA: Space Shuttle Mission Design + \item AstraZeneca: Collaborative Drug Discovery + \item ForecastWatch.com: Helps Meteorologists + \item Industrial Light \& Magic: Runs on Python + \item Zope: Commercial grade Toolkit + \item Plone: Professional high feature CMS + \item RedHat: install scripts, sys-admin tools + \item Django: A great web application framework + \item Google: A strong python shop + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{To sum up, python is\ldots} + \begin{itemize} + \item dynamically typed, interpreted $\rightarrow$ rapid testing/prototyping + \item powerful, very high level + \item has full introspection + \item Did we mention powerful? + \end{itemize} + \begin{block}{But \ldots} + may be wanting in performance. specialised resources such as SWIG, \alert{Cython} are available + \end{block} + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 15m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\section{Python} + +\subsection{Getting Started} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> print 'Hello Python' +>>> print 3124 * 126789 +>>> 1786 % 12 +>>> 3124 * 126789 +>>> a = 3124 * 126789 +>>> big = 12345678901234567890 ** 3 +>>> verybig = big * big * big * big +>>> 12345**6, 12345**67, 12345**678 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> s = 'Hello ' +>>> p = 'World' +>>> s + p +>>> s * 12 +>>> s * s +>>> s + p * 12, (s + p)* 12 +>>> s * 12 + p * 12 +>>> 12 * s + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> 17/2 +>>> 17/2.0 +>>> 17.0/2 +>>> 17.0/8.5 +>>> int(17/2.0) +>>> float(17/2) +>>> str(17/2.0) +>>> round( 7.5 ) + \end{lstlisting} + \begin{block}{Mini exercise} + Round a float to the nearest integer, using \texttt{int()}? + \end{block} +\end{frame} + +\begin{frame}{Midi exercises} + \begin{center} + \begin{itemize} + \item What does this do? + \item \texttt{round(amount * 10) /10.0 } + \end{itemize} + \end{center} +\end{frame} + +\begin{frame}{More exercises?} + \begin{center} + \begin{block}{Round sums} + How to round a number to the nearest 5 paise?\\ + \begin{description} + \item[Remember] 17.23 $\rightarrow$ 17.25,\\ while 17.22 $\rightarrow$ 17.20\\ + \end{description} + How to round a number to the nearest 20 paise? + \end{block} + \end{center} +\end{frame} + +\begin{frame}[fragile] {A question of good style} + \begin{lstlisting} + amount = 12.68 + denom = 0.05 + nCoins = round(amount/denom) + rAmount = nCoins * denom + \end{lstlisting} + \pause + \begin{block}{Style Rule \#1} + Naming is 80\% of programming + \end{block} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item Case sensitive + \item Dynamically typed $\Rightarrow$ need not specify a type + \begin{lstlisting} +a = 1 +a = 1.1 +a = "Now I am a string!" + \end{lstlisting} + \item Comments: + \begin{lstlisting} +a = 1 # In-line comments +# Comment in a line to itself. +a = "# This is not a comment!" + \end{lstlisting} + \end{itemize} + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 30m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Data types} +\begin{frame} + \frametitle{Basic types} + \begin{itemize} + \item numbers: float, int, long, complex + \item strings + \item boolean + \end{itemize} + \begin{block}{Also to be discussed later} + tuples, lists, dictionaries, functions, objects\ldots + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Numbers} + \vspace*{-0.25in} + \begin{lstlisting} +>>> a = 1 # Int. +>>> l = 1000000L # Long +>>> e = 1.01325e5 # float +>>> f = 3.14159 # float +>>> c = 1+1j # Complex! +>>> print f*c/a +(3.14159+3.14159j) +>>> print c.real, c.imag +1.0 1.0 +>>> abs(c) +1.4142135623730951 +>>> abs( 8 - 9.5 ) +1.5 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Boolean} + \begin{lstlisting} +>>> t = True +>>> f = not t +False +>>> f or t +True +>>> f and t +False + \end{lstlisting} + \begin{block}{Try:} + NOT True\\ + not TRUE + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Relational and logical operators} + \begin{lstlisting} +>>> a, b, c = -1, 0, 1 +>>> a == b +False +>>> a <= b +True +>>> a + b != c +True +>>> a < b < c +True +>>> c >= a + b +True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Strings} + \begin{lstlisting} +s = 'this is a string' +s = 'This one has "quotes" inside!' +s = "I have 'single-quotes' inside!" +l = "A string spanning many lines\ +one more line\ +yet another" +t = """A triple quoted string does +not need to be escaped at the end and +"can have nested quotes" etc.""" + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More Strings} + \vspace*{-0.2in} + \begin{lstlisting} +>>> w = "hello" +>>> print w[0] + w[2] + w[-1] +hlo +>>> len(w) # guess what +5 +>>> s = u'Unicode strings!' +>>> # Raw strings (note the leading 'r') +... r_s = r'A string $\alpha \nu$' + \end{lstlisting} +\pause + \begin{lstlisting} +>>> w[0] = 'H' # Can't do that! +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: object does not support item assignment + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Let us switch to IPython} + Why? + \begin{block} + {Better help (and a lot more)} + Tab completion\\ + ?\\ + .?\\ + object.function? + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More on strings} + \begin{lstlisting} +In [1]: a = 'hello world' +In [2]: a.startswith('hell') +Out[2]: True +In [3]: a.endswith('ld') +Out[3]: True +In [4]: a.upper() +Out[4]: 'HELLO WORLD' +In [5]: a.upper().lower() +Out[5]: 'hello world' + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Still with strings} + \begin{lstlisting} +In [6]: a.split() +Out[6]: ['hello', 'world'] +In [7]: ''.join(['a', 'b', 'c']) +Out[7]: 'abc' +In [8] 'd' in ''.join( 'a', 'b', 'c') +Out[8]: False + \end{lstlisting} + \begin{block}{Try:} + \texttt{a.split( 'o' )}\\ + \texttt{'x'.join( a.split( 'o' ) )} + \end{block} +\end{frame} + +\begin{frame}[fragile]{Surprise! strings!!} + \begin{lstlisting} +In [11]: x, y = 1, 1.2 +In [12]: 'x is %s, y is %s' %(x, y) +Out[12]: 'x is 1, y is 1.234' + \end{lstlisting} + \begin{block}{Try:} + \texttt{'x is \%d, y is \%f' \%(x, y) }\\ + \texttt{'x is \%3d, y is \%4.2f' \%(x, y) } + \end{block} + \small +\url{docs.python.org/lib/typesseq-strings.html}\\ +\end{frame} + +\begin{frame} + {Interlude} + \begin{block} + {A classic problem} + How to interchange values of two variables? Please note that the type of either variable is unknown and it is not necessary that both be of the same type even! + \end{block} + \inctime{30} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 25 m+ Interlude break 5 mins, running 60m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Control flow} +\begin{frame} + \frametitle{Control flow constructs} + \begin{itemize} + \item \kwrd{if/elif/else}: branching + \item \kwrd{while}: looping + \item \kwrd{for}: iterating + \item \kwrd{break, continue}: modify loop + \item \kwrd{pass}: syntactic filler + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic conditional flow} + \begin{lstlisting} +In [21]: a = 7 +In [22]: b = 8 +In [23]: if a > b: + ....: print 'Hello' + ....: else: + ....: print 'World' + ....: + ....: +World + \end{lstlisting} + Let us switch to creating a file +\end{frame} + +\begin{frame} + {Creating python files} + \begin{itemize} + \item aka scripts + \item use your editor + \item Note that white space is the way to specify blocks! + \item extension \typ{.py} + \item run with \texttt{python hello.py} at the command line + \item in IPython\ldots + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{If...elif...else} example} +\begin{lstlisting} +x = int(raw_input("Enter an integer:")) +if x < 0: + print 'Be positive!' +elif x == 0: + print 'Zero' +elif x == 1: + print 'Single' +else: + print 'More' +\end{lstlisting} +\end{frame} + +\begin{frame}{Simple IO} + \begin{block} + {Console Input} + \texttt{raw\_input(}) waits for user input.\\Prompt string is optional.\\ + All keystrokes are Strings!\\\texttt{int()} converts string to int. + \end{block} + \begin{block} + {Console output} + \texttt{print} is straight forward. Major point to remember is the distinction between \texttt{print x} and \texttt{print x,} + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic looping} + \begin{lstlisting} +# Fibonacci series: +# the sum of two elements +# defines the next +a, b = 0, 1 +while b < 10: + print b, + a, b = b, a + b + +\end{lstlisting} +\typ{1 1 2 3 5 8}\\ +\alert{Recall it is easy to write infinite loops with \kwrd{while}} + \inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 80m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + \frametitle{Problem set 1} + \begin{itemize} + \item All the problems can be\\ + solved using \kwrd{if} and \kwrd{while} + \end{itemize} +\end{frame} + +\begin{frame}{Problem 1.1} + Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ +These are called $Armstrong$ numbers. +\end{frame} + +\begin{frame}{Problem 1.2 - Collatz sequence} +\begin{enumerate} + \item Start with an arbitrary (positive) integer. + \item If the number is even, divide by 2; if the number is odd multiply by 3 and add 1. + \item Repeat the procedure with the new number. + \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. +\end{enumerate} + Write a program that accepts the starting value and prints out the Collatz sequence. + +\end{frame} + +\begin{frame}{Problem 1.3 - Kaprekar's constant} + \begin{enumerate} + \item Take a four digit number--with at least two digits different. + \item Arrange the digits in ascending and descending order, giving A and D respectively. + \item Leave leading zeros in A! + \item Subtract A from D. + \item With the result, repeat from step 2. + \end{enumerate} + Write a program to accept a 4-digit number and display the progression to Kaprekar's constant. +\end{frame} + +\begin{frame}[fragile]{Problem 1.4} + Write a program that prints the following pyramid on the screen. + \begin{lstlisting} +1 +2 2 +3 3 3 +4 4 4 4 + \end{lstlisting} +The number of lines must be obtained from the user as input.\\ +\pause +When can your code fail? +\only<2->{\inctime{25}} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 25 m, running 105m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Functions} +\begin{frame}[fragile] +\frametitle{Functions: examples} + \begin{lstlisting} +def signum( r ): + """returns 0 if r is zero + -1 if r is negative + +1 if r is positive""" + if r < 0: + return -1 + elif r > 0: + return 1 + else: + return 0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: examples} + \begin{lstlisting} +def pad( n, size ): + """pads integer n with spaces + into a string of length size + """ + SPACE = ' ' + s = str( n ) + padSize = size - len( s ) + return padSize * SPACE + s + \end{lstlisting} +\pause +What about \%3d? +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} + \begin{lstlisting} +def what( n ): + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} +\begin{lstlisting} +def what( n ): + i = 1 + while i * i < n: + i += 1 + return i * i == n, i + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} + \begin{lstlisting} +def what( n, x ): + z = 1.0 + if n < 0: + x = 1.0 / x + n = -n + while n > 0: + if n % 2 == 1: + z *= x + n /= 2 + x *= x + return z + \end{lstlisting} +\end{frame} + +\begin{frame} + {Before writing a function} + \begin{itemize} + \item Builtin functions for various and sundry + \item \typ{abs, any, all, len, max, min} + \item \typ{pow, range, sum, type} + \item Refer here: + \url{http://docs.python.org/library/functions.html} + \end{itemize} + \inctime{15} +\end{frame} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 120m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame}{Problem set 2} + The focus is on writing functions and calling them. +\end{frame} + +\begin{frame}{Problem 2.1} + Write a function to return the gcd of two numbers. +\end{frame} + +\begin{frame}{Problem 2.2} +A pythagorean triad $(a,b,c)$ has the property $a^2 + b^2 = c^2$.\\By primitive we mean triads that do not `depend' on others. For example, (4,3,5) is a variant of (3,4,5) and hence is not primitive. And (10,24,26) is easily derived from (5,12,13) and should not be displayed by our program. \\ +Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100 +\end{frame} + +\begin{frame}{Problem 2.3} + Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\\For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square). +\end{frame} + +\begin{frame}{Problem 2.4} + The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. For example, the aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.\\ + Write a function that returns the aliquot number of a given number. +\end{frame} + +\begin{frame}{Problem 2.5} + A pair of numbers (a, b) is said to be \alert{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ + Example: \texttt{220, 284}\\ + Write a program that prints all five digit amicable pairs. + \inctime{30} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 30 m, running 150m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Lists} + +\begin{frame}[fragile] + \frametitle{List creation and indexing} +\begin{lstlisting} +>>> a = [] # An empty list. +>>> a = [1, 2, 3, 4] # More useful. +>>> len(a) +4 +>>> a[0] + a[1] + a[2] + a[-1] +10 +\end{lstlisting} + \begin{itemize} + \item Indices start with ? + \item Negative indices indicate ? + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: slices} + \begin{itemize} + \item Slicing is a basic operation + \item \typ{list[initial:final:step]} + \item The step is optional + \end{itemize} +\begin{lstlisting} +>>> a[1:3] # A slice. +[2, 3] +>>> a[1:-1] +[2, 3, 4] +>>> a[1:] == a[1:-1] +False +\end{lstlisting} +Explain last result +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: more slices} +\begin{lstlisting} +>>> a[0:-1:2] # Notice the step! +[1, 3] +>>> a[::2] +[1, 3] +>>> a[-1::-1] +\end{lstlisting} +What do you think the last one will do? + \emphbar{Note: Strings also use same indexing and slicing.} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: examples} +\begin{lstlisting} +>>> a = [1, 2, 3, 4] +>>> a[:2] +[1, 3] +>>> a[0:-1:2] +[1, 3] +\end{lstlisting} +\pause +\alert{Lists are mutable (unlike strings)} +\begin{lstlisting} +>>> a[1] = 20 +>>> a +[1, 20, 3, 4] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists are mutable and heterogenous} +\begin{lstlisting} +>>> a = ['spam', 'eggs', 100, 1234] +>>> a[2] = a[2] + 23 +>>> a +['spam', 'eggs', 123, 1234] +>>> a[0:2] = [1, 12] # Replace items +>>> a +[1, 12, 123, 1234] +>>> a[0:2] = [] # Remove items +>>> a.append( 12345 ) +>>> a +[123, 1234, 12345] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List methods} +\begin{lstlisting} +>>> a = ['spam', 'eggs', 1, 12] +>>> a.reverse() # in situ +>>> a +[12, 1, 'eggs', 'spam'] +>>> a.append(['x', 1]) +>>> a +[12, 1, 'eggs', 'spam', ['x', 1]] +>>> a.extend([1,2]) # Extend the list. +>>> a.remove( 'spam' ) +>>> a +[12, 1, 'eggs', ['x', 1], 1, 2] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List containership} + \begin{lstlisting} +>>> a = ['cat', 'dog', 'rat', 'croc'] +>>> 'dog' in a +True +>>> 'snake' in a +False +>>> 'snake' not in a +True +>>> 'ell' in 'hello world' +True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Tuples: immutable} +\begin{lstlisting} +>>> t = (0, 1, 2) +>>> print t[0], t[1], t[2], t[-1] +0 1 2 2 +>>> t[0] = 1 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: object does not support item + assignment +\end{lstlisting} +\begin{itemize} + \item Multiple return values are actually a tuple. + \item Exchange is tuple (un)packing +\end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{range()} function} + \begin{lstlisting} +>>> range(7) +[0, 1, 2, 3, 4, 5, 6] +>>> range( 3, 9) +[3, 4, 5, 6, 7, 8] +>>> range( 4, 17, 3) +[4, 7, 10, 13, 16] +>>> range( 5, 1, -1) +[5, 4, 3, 2] +>>> range( 8, 12, -1) +[] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for\ldots range(\ldots)} idiom} + \begin{lstlisting} +In [83]: for i in range(5): + ....: print i, i * i + ....: + ....: +0 0 +1 1 +2 4 +3 9 +4 16 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for}: the list companion} + + \begin{lstlisting} +In [84]: a = ['a', 'b', 'c'] +In [85]: for x in a: + ....: print x, chr( ord(x) + 10 ) + ....: +a k +b l +c m + \end{lstlisting} + Iterating over the list and not the index + reference\\ + what if you want the index? +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for}: the list companion} + \begin{lstlisting} +In [89]: for p, ch in enumerate( a ): + ....: print p, ch + ....: + ....: +0 a +1 b +2 c + \end{lstlisting} +Try: \typ{print enumerate(a)} +\inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 170m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + {Problem set 3} + As you can guess, idea is to use \kwrd{for}! +\end{frame} + +\begin{frame}{Problem 3.1} + Which of the earlier problems is simpler when we use \kwrd{for} instead of \kwrd{while}? +\end{frame} + +\begin{frame}{Problem 3.2} + Given an empty chessboard and one Bishop placed in any square, say (r, c), generate the list of all squares the Bishop could move to. +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.3} + + Given two real numbers \typ{a, b}, and an integer \typ{N}, write a + function named \typ{linspace( a, b, N)} that returns an ordered list + of \typ{N} points starting with \typ{a} and ending in \typ{b} and + equally spaced.\\ + + For example, \typ{linspace(0, 5, 11)}, should return, \\ +\begin{lstlisting} +[ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, + 3.0 , 3.5, 4.0 , 4.5, 5.0 ] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.4a (optional)} + +Use the \typ{linspace} function and generate a list of N tuples of the form\\ +\typ{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions,\begin{itemize} + \item \typ{f(x) = sin(x)} + \item \typ{f(x) = sin(x) + sin(10*x)}. +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.4b (optional)} + + Using the tuples generated earlier, determine the intervals where the roots of the functions lie. + + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 185m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{IO} + +\begin{frame}[fragile] + \frametitle{Simple tokenizing and parsing} + \begin{lstlisting} +s = """The quick brown fox jumped + over the lazy dog""" +for word in s.split(): + print word.capitalize() + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 4.1} + Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \\ + \begin{lstlisting} + [1,3,4,5,6,7,12,15,18,19,20,21] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File handling} +\begin{lstlisting} +>>> f = open('/path/to/file_name') +>>> data = f.read() # Read entire file. +>>> line = f.readline() # Read one line. +>>> f.close() # close the file. +\end{lstlisting} +Writing files +\begin{lstlisting} +>>> f = open('/path/to/file_name', 'w') +>>> f.write('hello world\n') +>>> f.close() +\end{lstlisting} +\begin{itemize} + \item Everything read or written is a string +\end{itemize} +\emphbar{Try \typ{file?} for more help} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File and \kwrd{for}} +\begin{lstlisting} +>>> f = open('/path/to/file_name') +>>> for line in f: +... print line +... +\end{lstlisting} +\end{frame} + +\begin{frame}{Problem 4.2} + The given file has lakhs of records in the form:\\ + \typ{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}\\ + Some entries may be empty. Read the data from this file and print the + name of the student with the maximum total marks. +\end{frame} + +\begin{frame}{Problem 4.3} + For the same data file compute the average marks in different + subjects, the student with the maximum mark in each subject and also + the standard deviation of the marks. Do this efficiently. + + \inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 205m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Modules} + +\begin{frame}[fragile] + {Modules} +\begin{lstlisting} +>>> sqrt(2) +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +NameError: name 'sqrt' is not defined +>>> import math +>>> math.sqrt(2) +1.4142135623730951 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {Modules} + \begin{itemize} + \item The \kwrd{import} keyword ``loads'' a module + \item One can also use: + \begin{lstlisting} +>>> from math import sqrt +>>> from math import * + \end{lstlisting} + \item What is the difference? + \item \alert{Use the later only in interactive mode} + \end{itemize} + \emphbar{Package hierarchies} + \begin{lstlisting} +>>> from os.path import exists + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Modules: Standard library} + \begin{itemize} + \item Very powerful, ``Batteries included'' + \item Some standard modules: + \begin{itemize} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib2}, \typ{smtplib} + \item System, Command line arguments: \typ{sys} + \item Operating system interface: \typ{os} + \item Regular expressions: \typ{re} + \item Compression: \typ{gzip}, \typ{zipfile}, and \typ{tarfile} + \item And a whole lot more! + \end{itemize} + \item Check out the Python Library reference: + \url{http://docs.python.org/library/} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + {Modules of special interest} + \begin{description}[matplotlibfor2d] + + \item[\typ{numpy}] Efficient, powerful numeric arrays + + \item[\typ{matplotlib}] Easy, interactive, 2D plotting + + \item[\typ{scipy}] statistics, optimization, integration, linear + algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + + \item[Mayavi] Easy, interactive, 3D plotting + + \end{description} +\end{frame} + +\begin{frame}[fragile] + {Creating your own modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \typ{.py} extension + \item This file becomes a module! + \item Accessible when in the current directory + \item Use \typ{cd} in IPython to change directory + + \item Naming your module + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- arith.py --- +def gcd(a, b): + if a%b == 0: return b + return gcd(b, a%b) +def lcm(a, b): + return a*b/gcd(a, b) +# ------------------ +>>> import arith +>>> arith.gcd(26, 65) +13 +>>> arith.lcm(26, 65) +130 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 5.1} + + Put all the functions you have written so far as part of the problems + into one module called \typ{iitb.py} and use this module from IPython. + +\inctime{20} +\end{frame} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 225m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + \frametitle{Did we meet the goal?} + \tableofcontents + % You might wish to add the option [pausesections] + \end{frame} + + \begin{frame} + {Tomorrow} + \begin{itemize} + \item Plotting: 2D, 3D + \item NumPy, SciPy + \item Dictionary, Set + \item Debugging + \item Testing + \item \ldots + \end{itemize} + 11:30--13:00 Discussion of answers to problems OPTIONAL + \end{frame} +\end{document} + + +\begin{frame}[fragile] + \frametitle{More on functions} + \begin{itemize} + \item Support default and keyword arguments + \item Scope of variables in the function is local + \item Mutable items are \alert{passed by reference} + \item First line after definition may be a documentation string + (\alert{recommended!}) + \item Function definition and execution defines a name bound to the + function + \item You \emph{can} assign a variable to a function! + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Functions: default arguments} + \begin{lstlisting} +def ask_ok(prompt, retries=4, complaint='Yes or no!'): + while True: + ok = raw_input(prompt) + if ok in ('y', 'ye', 'yes'): + return True + if ok in ('n', 'no', 'nop', 'nope'): + return False + retries = retries - 1 + if retries < 0: + raise IOError, 'bad user' + print complaint + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: keyword arguments} + \begin{lstlisting} +def parrot(voltage, state='a stiff', + action='voom', type='Norwegian Blue'): + print "-- This parrot wouldn't", action, + print "if you put", voltage, "Volts through it." + print "-- Lovely plumage, the", type + print "-- It's", state, "!" + +parrot(1000) +parrot(action = 'VOOOOOM', voltage = 1000000) +parrot('a thousand', state = 'pushing up the daisies') +parrot('a million', 'bereft of life', 'jump') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: arbitrary argument lists} + \begin{itemize} + \item Arbitrary number of arguments using \verb+*args+ or + \verb+*whatever+ + \item Keyword arguments using \verb+**kw+ + \item Given a tuple/dict how do you call a function? + \begin{itemize} + \item Using argument unpacking + \item For positional arguments: \verb+foo(*[5, 10])+ + \item For keyword args: \verb+foo(**{'a':5, 'b':10})+ + \end{itemize} + \end{itemize} +\begin{lstlisting} +def foo(a=10, b=100): + print a, b +def func(*args, **keyword): + print args, keyword +# Unpacking: +args = [5, 10] +foo(*args) +kw = {'a':5, 'b':10} +foo(**kw) +\end{lstlisting} +\end{frame} + +\subsection{Modules, exceptions, classes} + +\begin{frame} + \frametitle{Modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \typ{.py} extension + \item This file becomes a module! + \item Modules are searched in the following: + \begin{itemize} + \item Current directory + \item Standard: \typ{/usr/lib/python2.3/site-packages/} etc. + \item Directories specified in PYTHONPATH + \item \typ{sys.path}: current path settings (from the \typ{sys} + module) + \end{itemize} + \item The \typ{import} keyword ``loads'' a module + \item One can also use: + \mbox{\typ{from module import name1, name2, name2}}\\ + where \typ{name1} etc. are names in the module, ``module'' + \item \typ{from module import *} \ --- imports everything from module, + \alert{use only in interactive mode} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- foo.py --- +some_var = 1 +def fib(n): # write Fibonacci series up to n + """Print a Fibonacci series up to n.""" + a, b = 0, 1 + while b < n: + print b, + a, b = b, a+b +# EOF + +>>> import foo +>>> foo.fib(10) +1 1 2 3 5 8 +>>> foo.some_var +1 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Namespaces} + \begin{itemize} + \item A mapping from names to objects + \item Modules introduce a namespace + \item So do classes + \item The running script's namespace is \verb+__main__+ + \item A modules namespace is identified by its name + \item The standard functions (like \typ{len}) are in the + \verb+__builtin__+ namespace + \item Namespaces help organize different names and their bindings to + different objects + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Exceptions} + \begin{itemize} + \item Python's way of notifying you of errors + \item Several standard exceptions: \typ{SyntaxError}, \typ{IOError} + etc. + \item Users can also \typ{raise} errors + \item Users can create their own exceptions + \item Exceptions can be ``caught'' via \typ{try/except} blocks + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exception: examples} +\begin{lstlisting} +>>> 10 * (1/0) +Traceback (most recent call last): + File "<stdin>", line 1, in ? +ZeroDivisionError: integer division or modulo by zero +>>> 4 + spam*3 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +NameError: name 'spam' is not defined +>>> '2' + 2 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: cannot concatenate 'str' and 'int' objects +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exception: examples} +\begin{lstlisting} +>>> while True: +... try: +... x = int(raw_input("Enter a number: ")) +... break +... except ValueError: +... print "Invalid number, try again..." +... +>>> # To raise exceptions +... raise ValueError, "your error message" +Traceback (most recent call last): + File "<stdin>", line 2, in ? +ValueError: your error message +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: the big picture} + \begin{itemize} + \item Lets you create new data types + \item Class is a template for an object belonging to that class + \item Note: in Python a class is also an object + \item Instantiating a class creates an instance (an object) + \item An instance encapsulates the state (data) and behavior + (methods) + \item Allows you to define an inheritance hierarchy + \begin{itemize} + \item ``A Honda car \alert{is a} car.'' + \item ``A car \alert{is an} automobile.'' + \item ``A Python \alert{is a} reptile.'' + \end{itemize} + \item Programmers need to think OO + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: what's the big deal?} + \begin{itemize} + \item Lets you create objects that mimic a real problem being + simulated + \item Makes problem solving more natural and elegant + \item Easier to create code + \item Allows for code-reuse + \item Polymorphism + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Class definition and instantiation} + \begin{itemize} + \item Class definitions when executed create class objects + \item Instantiating the class object creates an instance of the + class + \end{itemize} +\footnotesize +\begin{lstlisting} +class Foo(object): + pass +# class object created. +# Create an instance of Foo. +f = Foo() +# Can assign an attribute to the instance +f.a = 100 +print f.a +100 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes \ldots} + \begin{itemize} + \item All attributes are accessed via the \typ{object.attribute} + syntax + \item Both class and instance attributes are supported + \item \emph{Methods} represent the behavior of an object: crudely + think of them as functions ``belonging'' to the object + \item All methods in Python are ``virtual'' + \item Inheritance through subclassing + \item Multiple inheritance is supported + \item No special public and private attributes: only good + conventions + \begin{itemize} + \item \verb+object.public()+: public + \item \verb+object._private()+ \& \verb+object.__priv()+: + non-public + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: examples} +\begin{lstlisting} +class MyClass(object): + """Example class (this is the class docstring).""" + i = 12345 # A class attribute + def f(self): + """This is the method docstring""" + return 'hello world' + +>>> a = MyClass() # creates an instance +>>> a.f() +'hello world' +>>> # a.f() is equivalent to MyClass.f(a) +... # This also explains why f has a 'self' argument. +... MyClass.f(a) +'hello world' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes (continued)} + \begin{itemize} + \item \typ{self} is \alert{conventionally} the first argument for a + method + \item In previous example, \typ{a.f} is a method object + \item When \typ{a.f} is called, it is passed the instance \typ{a} as + the first argument + \item If a method called \verb+__init__+ exists, it is called when + the object is created + \item If a method called \verb+__del__+ exists, it is called before + the object is garbage collected + \item Instance attributes are set by simply ``setting'' them in + \typ{self} + \item Other special methods (by convention) like \verb+__add__+ let + you define numeric types: + {\footnotesize \url{http://docs.python.org/ref/specialnames.html} + \\ \url{http://docs.python.org/ref/numeric-types.html} + } + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: examples} +\begin{lstlisting} +class Bag(MyClass): # Shows how to derive classes + def __init__(self): # called on object creation. + self.data = [] # an instance attribute + def add(self, x): + self.data.append(x) + def addtwice(self, x): + self.add(x) + self.add(x) +>>> a = Bag() +>>> a.f() # Inherited method +'hello world' +>>> a.add(1); a.addtwice(2) +>>> a.data +[1, 2, 2] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Derived classes} + \begin{itemize} + \item Call the parent's \verb+__init__+ if needed + \item If you don't need a new constructor, no need to define it in subclass + \item Can also use the \verb+super+ built-in function + \end{itemize} +\begin{lstlisting} +class AnotherBag(Bag): + def __init__(self): + # Must call parent's __init__ explicitly + Bag.__init__(self) + # Alternatively use this: + super(AnotherBag, self).__init__() + # Now setup any more data. + self.more_data = [] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: polymorphism} +\begin{lstlisting} +class Drawable(object): + def draw(self): + # Just a specification. + pass +\end{lstlisting} +\mode<presentation>{\pause} +\begin{lstlisting} +class Square(Drawable): + def draw(self): + # draw a square. +class Circle(Drawable): + def draw(self): + # draw a circle. +\end{lstlisting} +\mode<presentation>{\pause} +\begin{lstlisting} +class Artist(Drawable): + def draw(self): + for obj in self.drawables: + obj.draw() +\end{lstlisting} +\end{frame} + +\subsection{Miscellaneous} + +\begin{frame}[fragile] + \frametitle{Stand-alone scripts} +Consider a file \typ{f.py}: +\begin{lstlisting} +#!/usr/bin/env python +"""Module level documentation.""" +# First line tells the shell that it should use Python +# to interpret the code in the file. +def f(): + print "f" + +# Check if we are running standalone or as module. +# When imported, __name__ will not be '__main__' +if __name__ == '__main__': + # This is not executed when f.py is imported. + f() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List comprehensions} +\begin{lstlisting} +>>> veg = ['tomato', 'cabbage', 'carrot', 'potato'] +>>> [x.upper() for x in veg] +['TOMATO', 'CABBAGE', 'CARROT', 'POTATO'] +>>> vec = range(0, 8) +>>> even = [x for x in vec if x%2 == 0] +>>> even +[0, 2, 4, 6] +>>> [x*x for x in even] +[0, 4, 16, 36] +>>> odd = [x for x in vec if x%2 == 1] +>>> odd +[1, 3, 5, 7] +>>> [x*y for x in even for y in odd] +[0, 0, 0, 0, 2, 6, 10, 14, 4, 12, 20, 28, 6, 18,30,42] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features} + \begin{itemize} + \item Input and output caching: + \begin{itemize} + \item \verb+In+: a list of all entered input + \item \verb+Out+: a dict of all output + \item \verb+_+, \verb+__+, \verb+__+ are the last three results as + is \verb+_N+ + \item \verb+%hist [-n]+ macro shows previous history, \verb+-n+ + suppresses line number information + \end{itemize} + \item Log the session using \verb+%logstart+, \verb+%logon+ and + \verb+%logoff+ + \item \verb+%run [options] file[.py]+ -- running Python code + \begin{itemize} + \item \verb+%run -d [-b<N>]+: debug script with pdb + \verb+N+ is the line number to break at (defaults to 1) + \item \verb+%run -t+: time the script + \item \verb+%run -p+: Profile the script + \end{itemize} + \item \verb+%prun+ runs a statement/expression under the profiler + \item \verb+%macro [options] macro_name n1-n2 n3-n4 n6+ save specified + lines to a macro with name \verb+macro_name+ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features \ldots} + \begin{itemize} + \item \verb+%edit [options] [args]+: edit lines of code or file + specified in editor (configure editor via \verb+$EDITOR+) + \item \verb+%cd+ changes directory, see also \verb+%pushd, %popd, %dhist+ + \item Shell access + \begin{itemize} + \item \verb+!command+ runs a shell command and returns its output + \item \verb+files = %sx ls+ or \verb+files = !ls+ sets + \verb+files+ to all result of the \verb+ls+ command + \item \verb+%sx+ is quiet + \item \verb+!ls $files+ passes the \verb+files+ variable to the + shell command + \item \verb+%alias alias_name cmd+ creates an alias for a system + command + \end{itemize} + \item \verb+%colors+ lets you change the color scheme to + \verb+NoColor, Linux, LightBG+ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features \ldots} + \begin{itemize} + \item Use \verb+;+ at the end of a statement to suppress printing + output + \item \verb+%bookmark+: store a bookmarked location, for use with \verb+%cd+ + \item \verb+%who, %whos+: print information on variables + \item \verb+%save [options] filename n1-n2 n3-n4+: save lines to a + file + \item \verb+%time statement+: Time execution of a Python statement or + expression + \item \verb+%timeit [-n<N> -r<R> [-t|-c]] statement+: time execution + using Python's timeit module + \item Can define and use profiles to setup IPython differently: + \verb+math, scipy, numeric, pysh+ etc. + \item \verb+%magic+: \alert{Show help on all magics} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File handling} +\begin{lstlisting} +>>> # Reading files: +... f = open('/path/to/file_name') +>>> data = f.read() # Read entire file. +>>> line = f.readline() # Read one line. +>>> # Read entire file appending each line into a list +... lines = f.readlines() +>>> f.close() # close the file. +>>> # Writing files: +... f = open('/path/to/file_name', 'w') +>>> f.write('hello world\n') +\end{lstlisting} + \begin{itemize} + \item \typ{tell()}: returns int of current position + \item \typ{seek(pos)}: moves current position to specified byte + \item Call \typ{close()} when done using a file + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Math} + \begin{itemize} + \item \typ{math} module provides basic math routines for + floats + \item \typ{cmath} module provides math routies for complex + numbers + \item \typ{random}: provides pseudo-random number generators + for various distributions + \item These are always available and part of the standard library + \item More serious math is provided by the NumPy/SciPy modules -- + these are not standard and need to be installed separately + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Timing and profiling} + \begin{itemize} + \item Timing code: use the \typ{time} module + \item Read up on \typ{time.time()} and \typ{time.clock()} + \item \typ{timeit}: is a better way of doing timing + \item IPython has handy \typ{time} and \typ{timeit} macros (type + \typ{timeit?} for help) + \item IPython lets you debug and profile code via the \typ{run} + macro (type \typ{run?} on the prompt to learn more) + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item \typ{dir([object])} function: attributes of given object + \item \typ{type(object)}: returns type information + \item \typ{str(), repr()}: convert object to string representation + \item \typ{isinstance, issubclass} + \item \typ{assert} statements let you do debugging assertions in + code + \item \typ{csv} module: reading and writing CSV files + \item \typ{pickle}: lets you save and load Python objects + (\alert{serialization}) + \item \typ{sys.argv}: command line arguments + \item \typ{os.path}: common path manipulations + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Test driven development (TDD)} + \begin{itemize} + \item Why? + \begin{itemize} + + \item Forces you to write reusable code! + + \item Think about the API + + \item More robust + + \item Makes refactoring very easy + + \end{itemize} + \item How? Python offers three major ways of doing this + \begin{itemize} + \item doctest + \item unittest + \item nosetest (and similar like py.test) + \end{itemize} + + \item Test every piece of functionality you offer + + \item This isn't a formal introduction but more a practical one + + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Unit test} +\begin{lstlisting} +import unittest + +class MyTestCase(unittest.TestCase): + def setUp(self): + # Called *before* each test_* + def tearDown(self): + # Called *after* each test_* + def test_something(self): + "docstring" + # Test code. + self.assertEqual(x, y) + self.assertRaises(ValueError, func, arg1, arg2 ...) + +if __name__ == '__main__': + unittest.main() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Nosetest} +\begin{lstlisting} +import particle +def test_particle(): + # Use asserts here. + p = particle.Particle(1.0) + assert p.property[0] == 1.0 + assert p.property[2] == 0.0 + +if __name__ == '__main__': + import nose + nose.main() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Testing} + \begin{itemize} + \item More details: see library reference and search for nosetest + \end{itemize} +\end{frame} + +\section{Numerics \& Plotting} + +\subsection{NumPy Arrays} + +\newcommand{\num}{\texttt{numpy}} + +\begin{frame} + \frametitle{The \num\ module} + \begin{itemize} + \item Manipulating large Python lists for scientific computing is + \alert{slow} + \item Most complex computations can be reduced to a few standard + operations + \item The \num\ module provides: + \begin{itemize} + \item An efficient and powerful array type for various common data + types + \item Abstracts out the most commonly used standard operations on + arrays + \end{itemize} + \item Numeric was the first, then came \texttt{numarray}. + \texttt{numpy} is the latest and is the future + \item This course uses \num\ and only covers the absolute basics + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Basic concepts} + \begin{itemize} + \item \num\ arrays are of a fixed size (\typ{arr.size}) and have the + same type (\typ{arr.dtype}) + \item \num\ arrays may have arbitrary dimensionality + \item The \typ{shape} of an array is the extent (length) of the + array along each dimension + \item The \typ{rank(arr)} of an array is the ``dimensionality'' of the + array + \item The \typ{arr.itemsize} is the number of bytes (8-bits) used for + each element of the array + \item \alert{Note:} The \typ{shape} and \typ{rank} may change as + long as the \typ{size} of the array is fixed + \item \alert{Note:} \typ{len(arr) != arr.size} in general + \item \alert{Note:} By default array operations are performed + \alert{elementwise} + \item Indices start from 0 + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Examples of \num} +\begin{lstlisting} +# Simple array math example +>>> from numpy import * +>>> a = array([1,2,3,4]) +>>> b = array([2,3,4,5]) +>>> a + b # Element wise addition! +array([3, 5, 7, 9]) + +>>> print pi, e # Pi and e are defined. +3.14159265359 2.71828182846 +# Create array from 0 to 10 +>>> x = arange(0.0, 10.0, 0.05) +>>> x *= 2*pi/10 # multiply array by scalar value +array([ 0.,0.0314,...,6.252]) +# apply functions to array. +>>> y = sin(x) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More examples of \num} +\vspace*{-8pt} +\begin{lstlisting} +# Size, shape, rank, type etc. +>>> x = array([1., 2, 3, 4]) +>>> size(x) +4 +>>> x.dtype # or x.dtype.char +'d' +>>> x.shape +(4,) +>>> print rank(x), x.itemsize +1 8 +>>> x.tolist() +[1.0, 2.0, 3.0, 4.0] +# Array indexing +>>> x[0] = 10 +>>> print x[0], x[-1] +10.0 4.0 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Multi-dimensional arrays} +\begin{lstlisting} +>>> a = array([[ 0, 1, 2, 3], +... [10,11,12,13]]) +>>> a.shape # (rows, columns) +(2, 4) +# Accessing and setting values +>>> a[1,3] +13 +>>> a[1,3] = -1 +>>> a[1] # The second row +array([10,11,12,-1]) + +# Flatten/ravel arrays to 1D arrays +>>> a.flat # or ravel(a) +array([0,1,2,3,10,11,12,-1]) +# Note: flat references original memory +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Slicing arrays} +\begin{lstlisting} +>>> a = array([[1,2,3], [4,5,6], [7,8,9]]) +>>> a[0,1:3] +array([2, 3]) +>>> a[1:,1:] +array([[5, 6], + [8, 9]]) +>>> a[:,2] +array([3, 6, 9]) +# Striding... +>>> a[0::2,0::2] +array([[1, 3], + [7, 9]]) +# All these slices are references to the same memory! +\end{lstlisting} +\end{frame} + +% \begin{frame}[fragile] +% \frametitle{Array types and typecodes} +% \begin{tabular}[c]{|c|c|p{2.75in}|} +% \hline +% Character & Bits (bytes) & Type name \\ +% \hline +% D & 128 (16) & \typ{Complex, Complex64}\\ +% F & 64 (8) & \typ{Complex0, Complex8, Complex16} \\ +% d & 64 (8) & \typ{Float, Float64} \\ +% f & 32 (4) & \typ{Float0, Float8, Float16} \\ +% i & 32 (4) & \typ{Int32} \\ +% l & 32 (4) & \typ{Int} \\ +% O & 4 (1) & \typ{PyObject} \\ +% %b 8 (1) UnsignedInt8 +% %1 (one) 8 (1) Int8 +% %s 16 (2) Int16 +% \hline +% \end{tabular} +% \begin{lstlisting} +% # Examples +% >>> f = array([1,2,3], Float32) +% >>> c = array([1,2,3], Complex32) +% >>> print f, c +% [ 1. 2. 3.] [ 1.+0.j 2.+0.j 3.+0.j] +% \end{lstlisting} +% \end{frame} + +\begin{frame}[fragile] + \frametitle{Array creation functions} + \begin{itemize} + \item \typ{array(object, dtype=None, copy=1,order=None, subok=0,ndmin=0)} + \item \typ{arange(start, stop=None, step=1, dtype=None)} + \item \typ{linspace(start, stop, num=50, endpoint=True, retstep=False)} + \item \typ{ones(shape, dtype=None, order='C')} + \item \typ{zeros((d1,...,dn),dtype=float,order='C')} + \item \typ{identity(n)} + \item \typ{empty((d1,...,dn),dtype=float,order='C')} + \item \typ{ones\_like(x)}, \typ{zeros\_like(x)}, \typ{empty\_like(x)} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Array math} + \begin{itemize} + \item Basic \alert{elementwise} math (given two arrays \typ{a, b}): + \begin{itemize} + \item \typ{a + b $\rightarrow$ add(a, b)} + \item \typ{a - b, $\rightarrow$ subtract(a, b)} + \item \typ{a * b, $\rightarrow$ multiply(a, b)} + \item \typ{a / b, $\rightarrow$ divide(a, b)} + \item \typ{a \% b, $\rightarrow$ remainder(a, b)} + \item \typ{a ** b, $\rightarrow$ power(a, b)} + \end{itemize} + \item Inplace operators: \typ{a += b}, or \typ{add(a, b, + a)} etc. + \item Logical operations: \typ{equal (==)}, \typ{not\_equal (!=)}, + \typ{less (<)}, \typ{greater (>)} etc. + \item Trig and other functions: \typ{sin(x), arcsin(x), sinh(x), + exp(x), sqrt(x)} etc. + \item \typ{sum(x, axis=0), product(x, axis=0)}: sum and product of array elements + \item \typ{dot(a, b)} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Advanced} + \begin{itemize} + \item Only scratched the surface of \num + \item Ufunc methods: \typ{reduce, accumulate, outer, reduceat} + \item Typecasting + \item More functions: \typ{take, choose, where, compress, + concatenate} + \item Array broadcasting and \typ{None} + \end{itemize} +\end{frame} + +\subsection{Plotting: Matplotlib} + +\begin{frame} + \frametitle{About \texttt{matplotlib}} + \begin{itemize} + \item Easy to use, scriptable, ``Matlab-like'' 2D plotting + \item Publication quality figures and interactive capabilities + \item Plots, histograms, power spectra, bar charts, errorcharts, + scatterplots, etc. + \item Also does polar plots, maps, contours + \item Support for simple \TeX\ markup + \item Multiple output backends (images, EPS, SVG, wx, Agg, Tk, GTK) + \item Cross-platform: Linux, Win32, Mac OS X + \item Good idea to use via IPython: \typ{ipython -pylab} + \item From scripts use: \typ{import pylab} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{More information} + \begin{itemize} + \item More information here: \url{http://matplotlib.sf.net} + \item \url{http://matplotlib.sf.net/tutorial.html} + \item \url{http://matplotlib.sf.net/screenshots.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting with \texttt{matplotlib}} +\begin{lstlisting} +>>> x = arange(0, 2*pi, 0.05) +>>> plot(x, sin(x)) # Same as plot(x, sin(x), 'b-') +>>> plot(x, sin(x), 'ro') +>>> axis([0,2*pi, -1,1]) +>>> xlabel(r'$\chi$', color='g') +>>> ylabel(r'sin($\chi$)', color='r') +>>> title('A simple figure', fontsize=20) +>>> savefig('/tmp/test.eps') +# Multiple plots in one figure +>>> t = arange(0.0, 5.2, 0.2) +# red dashes, blue squares and green triangles +>>> plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting \ldots} +\begin{lstlisting} +# Set properties of objects: +>>> plot(x, sin(x), linewidth=2.0, color='r') +>>> l, = plot(x, sin(x)) +>>> setp(l, linewidth=2.0, color='r') +>>> l.set_linewidth(2.0); l.set_color('r') +>>> draw() # Redraws current figure. +>>> setp(l) # Prints available properties +>>> close() # Closes the figure. +# Multiple figures: +>>> figure(1); plot(x, sin(x)) +>>> figure(2); plot(x, tanh(x)) +>>> figure(1); title('Easy as 1,2,3') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting \ldots} +\begin{lstlisting} +>>> figure(1) +>>> subplot(211) # Same as subplot(2, 1, 1) +>>> plot(x, cos(5*x)*exp(-x)) +>>> subplot(2, 1, 2) +>>> plot(x, cos(5*x), 'r--', label='cosine') +>>> plot(x, sin(5*x), 'g--', label='sine') +>>> legend() # Or legend(['cosine', 'sine']) +>>> text(1,0, '(1,0)') +>>> axes = gca() # Current axis +>>> fig = gcf() # Current figure +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{X-Y plot} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/xyplot} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +t1 = arange(0.0, 5.0, 0.1) +t2 = arange(0.0, 5.0, 0.02) +t3 = arange(0.0, 2.0, 0.01) +subplot(211) +plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', + t2, cos(2*pi*t2)*exp(-t2), 'k') +grid(True) +title('A tale of 2 subplots') +ylabel('Damped') +subplot(212) +plot(t3, cos(2*pi*t3), 'r--') +grid(True) +xlabel('time (s)') +ylabel('Undamped') +\end{lstlisting} + \end{block} + \end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Errorbar} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/errorbar} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +t = arange(0.1, 4, 0.1) +s = exp(-t) +e = 0.1*abs(randn(len(s))) +f = 0.1*abs(randn(len(s))) +g = 2*e +h = 2*f +errorbar(t, s, [e,g], f, fmt='o') +xlabel('Distance (m)') +ylabel('Height (m)') +title('Mean and standard error '\ + 'as a function of distance') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Semi-log and log-log plots} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/log} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +dt = 0.01 +t = arange(dt, 20.0, dt) +subplot(311) +semilogy(t, exp(-t/5.0)) +ylabel('semilogy') +grid(True) +subplot(312) +semilogx(t, sin(2*pi*t)) +ylabel('semilogx') +grid(True) +# minor grid on too +gca().xaxis.grid(True, which='minor') +subplot(313) +loglog(t, 20*exp(-t/10.0), basex=4) +grid(True) +ylabel('loglog base 4 on x') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Histogram} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/histogram} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +mu, sigma = 100, 15 +x = mu + sigma*randn(10000) +# the histogram of the data +n, bins, patches = hist(x, 100, normed=1) +# add a 'best fit' line +y = normpdf( bins, mu, sigma) +l = plot(bins, y, 'r--', linewidth=2) +xlim(40, 160) +xlabel('Smarts') +ylabel('P') +title(r'$\rm{IQ:}\/ \mu=100,\/ \sigma=15$') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Bar charts} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/barchart} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +N = 5 +menMeans = (20, 35, 30, 35, 27) +menStd = ( 2, 3, 4, 1, 2) +# the x locations for the groups +ind = arange(N) +# the width of the bars +width = 0.35 +p1 = bar(ind, menMeans, width, + color='r', yerr=menStd) +womenMeans = (25, 32, 34, 20, 25) +womenStd = ( 3, 5, 2, 3, 3) +p2 = bar(ind+width, womenMeans, width, + color='y', yerr=womenStd) +ylabel('Scores') +title('Scores by group and gender') +xticks(ind+width, + ('G1', 'G2', 'G3', 'G4', 'G5')) +xlim(-width,len(ind)) +yticks(arange(0,41,10)) +legend((p1[0], p2[0]), + ('Men', 'Women'), shadow=True) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Pie charts} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.4in} + \includegraphics[height=2.0in, interpolate=true]{data/piechart} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +# make a square figure and axes +figure(1, figsize=(8,8)) +ax = axes([0.1, 0.1, 0.8, 0.8]) +labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' +fracs = [15,30,45, 10] +explode=(0, 0.05, 0, 0) +pie(fracs, explode=explode, labels=labels, + autopct='%1.1f%%', shadow=True) +title('Raining Hogs and Dogs', + bbox={'facecolor':'0.8', 'pad':5}) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Scatter plots} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.4in} + \includegraphics[height=2in, interpolate=true]{data/scatter} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +N = 30 +x = 0.9*rand(N) +y = 0.9*rand(N) +# 0 to 10 point radiuses +area = pi*(10 * rand(N))**2 +volume = 400 + rand(N)*450 +scatter(x,y,s=area, marker='o', c=volume, + alpha=0.75) +xlabel(r'$\Delta_i$', size='x-large') +ylabel(r'$\Delta_{i+1}$', size='x-large') +title(r'Volume and percent change') +grid(True) +colorbar() +savefig('scatter') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Polar} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/polar} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +figure(figsize=(8,8)) +ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, + axisbg='#d5de9c') +r = arange(0,1,0.001) +theta = 2*2*pi*r +polar(theta, r, color='#ee8d18', lw=3) +# the radius of the grid labels +setp(ax.thetagridlabels, y=1.075) +title(r"$\theta=4\pi r", fontsize=20) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Contours} + \begin{columns} + \column{0.45\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/contour} + \column{0.525\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +x = arange(-3.0, 3.0, 0.025) +y = arange(-2.0, 2.0, 0.025) +X, Y = meshgrid(x, y) +Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) +# difference of Gaussians +Z = 10.0 * (Z2 - Z1) +im = imshow(Z, interpolation='bilinear', + origin='lower', + cmap=cm.gray, extent=(-3,3,-2,2)) +levels = arange(-1.2, 1.6, 0.2) +# label every second level +clabel(CS, levels[1::2], inline=1, + fmt='%1.1f', fontsize=14) +CS = contour(Z, levels, + origin='lower', + linewidths=2, + extent=(-3,3,-2,2)) +# make a colorbar for the contour lines +CB = colorbar(CS, shrink=0.8, extend='both') +title('Lines with colorbar') +hot(); flag() +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Velocity vectors} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/quiver} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +X,Y = meshgrid(arange(0,2*pi,.2), + arange(0,2*pi,.2) ) +U = cos(X) +V = sin(Y) +Q = quiver(X[::3, ::3], Y[::3, ::3], + U[::3, ::3], V[::3, ::3], + color='r', units='x', + linewidths=(2,), + edgecolors=('k'), + headaxislength=5 ) +qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', + fontproperties= + {'weight': 'bold'}) +axis([-1, 7, -1, 7]) +title('triangular head; scale '\ + 'with x view; black edges') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Maps} + \includegraphics[height=2.5in, interpolate=true]{data/plotmap} + \begin{center} + \tiny + For details see \url{http://matplotlib.sourceforge.net/screenshots/plotmap.py} + \end{center} +\end{frame} + + +\subsection{SciPy} + +\begin{frame} + \frametitle{Using \texttt{SciPy}} + \begin{itemize} + \item SciPy is Open Source software for mathematics, science, and + engineering + \item \typ{import scipy} + \item Built on NumPy + \item Provides modules for statistics, optimization, integration, + linear algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + \item Used widely by scientists world over + \item Details are beyond the scope of this tutorial + \end{itemize} +\end{frame} + +\section{Standard library} + +\subsection{Quick Tour} + +\begin{frame} + \frametitle{Standard library} + \begin{itemize} + \item Very powerful + \item ``Batteries included'' + \item Example standard modules taken from the tutorial + \begin{itemize} + \item Operating system interface: \typ{os} + \item System, Command line arguments: \typ{sys} + \item Regular expressions: \typ{re} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib2}, \typ{smtplib} + \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, + \typ{zipfile}, and \typ{tarfile} + \item Unit testing: \typ{doctest} and \typ{unittest} + \item And a whole lot more! + \end{itemize} + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import os +>>> os.system('date') +Fri Jun 10 22:13:09 IST 2005 +0 +>>> os.getcwd() +'/home/prabhu' +>>> os.chdir('/tmp') +>>> import os +>>> dir(os) +<returns a list of all module functions> +>>> help(os) +<extensive manual page from module's docstrings> +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import sys +>>> # Print the list of command line args to Python +... print sys.argv +[''] +>>> import re # Regular expressions +>>> re.findall(r'\bf[a-z]*', +... 'which foot or hand fell fastest') +['foot', 'fell', 'fastest'] +>>> re.sub(r'(\b[a-z]+) \1', r'\1', +... 'cat in the the hat') +'cat in the hat' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import math +>>> math.cos(math.pi / 4.0) +0.70710678118654757 +>>> math.log(1024, 2) +10.0 +>>> import random +>>> random.choice(['apple', 'pear', 'banana']) +'pear' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import urllib2 +>>> f = urllib2.urlopen('http://www.python.org/') +>>> print f.read(100) +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<?xml-stylesheet href="./css/ht2html +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import zlib +>>> s = 'witch which has which witches wrist watch' +>>> len(s) +41 +>>> t = zlib.compress(s) +>>> len(t) +37 +>>> zlib.decompress(t) +'witch which has which witches wrist watch' +>>> zlib.crc32(t) +-1438085031 +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Introduced Python + \item Basic syntax + \item Basic types and data structures + \item Control flow + \item Functions + \item Modules + \item Exceptions + \item Classes + \item Standard library + \end{itemize} +\end{frame} + +\end{document} + +\subsection{Basic data structures} +\begin{frame}{Lists} + \begin{itemize} + \item \texttt{species = [ 'humans', 'orcs', 'elves', 'dwarves' ]} + \item \texttt{ ids = [ 107, 109, 124, 141, 142, 144 ]} + \item \texttt{ oneliners = [ 'I will be back', 'Do or do not! No try!!', 42 ] } + \end{itemize} + + \begin{block}{List operations} + ids + [ 100, 102 ]\\ + species.append( 'unicorns')\\ + print oneliners[ 1 ]\\ + look up \alert{docs.python.org/tutorial/datastructures.html} + \end{block} +\end{frame} +\end{document} +\section{Python Tutorial} +\subsection{Preliminaries} +\begin{frame} + \frametitle{Using the interpreter} + \begin{itemize} + \item Starting up: \typ{python} or \typ{ipython} + \item Quitting: \typ{Control-D} or \typ{Control-Z} (on Win32) + \item Can use it like a calculator + \item Can execute one-liners via the \typ{-c} option: + \typ{python -c "print 'hello world'"} + \item Other options via \typ{python -h} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{IPython} + \begin{itemize} + \item Recommended interpreter, IPython: + \url{http://ipython.scipy.org} + \item Better than the default Python shell + \item Supports tab completion by default + \item Easier object introspection + \item Shell access! + \item Command system to allow extending its own behavior + \item Supports history (across sessions) and logging + \item Can be embedded in your own Python code + \item Support for macros + \item A flexible framework for your own custom interpreter + \item Other miscellaneous conveniences + \item We'll get back to this later + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic IPython features} + \begin{itemize} + \item Startup: \verb+ipython [options] files+ + \begin{itemize} + \item \verb+ipython [-wthread|-gthread|-qthread]+: + Threading modes to support wxPython, pyGTK and Qt + \item \verb+ipython -pylab+: Support for matplotlib + \end{itemize} + \item TAB completion: + \begin{itemize} + \item Type \verb+object_name.<TAB>+ to see list of options + \item Also completes on file and directory names + \end{itemize} + \item \verb+object?+ shows docstring/help for any Python object + \item \verb+object??+ presents more docs (and source if possible) + \item Debugging with \verb+%pdb+ magic: pops up pdb on errors + \item Access history (saved over earlier sessions also) + \begin{itemize} + \item Use \texttt{<UpArrow>}: move up history + \item Use \texttt{<Ctrl-r> string}: search history backwards + \item Use \texttt{Esc >}: get back to end of history + \end{itemize} + \item \verb+%run [options] file[.py]+ lets you run Python code + \end{itemize} +\end{frame} +% LocalWords: BDFL Guido Rossum PSF Nokia OO Zope CMS RedHat SciPy MayaVi spam +% LocalWords: IPython ipython stdin TypeError dict int elif PYTHONPATH IOError +% LocalWords: namespace Namespaces SyntaxError ZeroDivisionError NameError str +% LocalWords: ValueError subclassed def + + + \item Types are of two kinds: \alert{mutable} and \alert{immutable} + \item Immutable types: numbers, strings, \typ{None} and tuples + \item Immutables cannot be changed ``in-place'' + \item Mutable types: lists, dictionaries, instances, etc. + \item Mutable objects can be ``changed'' + \end{itemize} + + +\begin{frame} + \frametitle{Important!} + \begin{itemize} + \item Assignment to an object is by reference + \item Essentially, \alert{names are bound to objects} + \end{itemize} +\end{frame} + + +\end{document} +\begin{frame}[fragile] + \frametitle{Dictionaries} + \begin{itemize} + \item Associative arrays/mappings + \item Indexed by ``keys'' (keys must be immutable) + \item \typ{dict[key] = value} + \item \typ{keys()} returns all keys of the dict + \item \typ{values()} returns the values of the dict + \item \verb+has_key(key)+ returns if \typ{key} is in the dict + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries: example} + \begin{lstlisting} +>>> tel = {'jack': 4098, 'sape': 4139} +>>> tel['guido'] = 4127 +>>> tel +{'sape': 4139, 'guido': 4127, 'jack': 4098} +>>> tel['jack'] +4098 +>>> del tel['sape'] +>>> tel['irv'] = 4127 +>>> tel +{'guido': 4127, 'irv': 4127, 'jack': 4098} +>>> tel.keys() +['guido', 'irv', 'jack'] +>>> tel.has_key('guido') +True + \end{lstlisting} +\end{frame} + +\subsection{Control flow, functions} + + + +\begin{frame}[fragile] + \frametitle{\typ{If} example} + \begin{lstlisting} +>>> a = ['cat', 'window', 'defenestrate'] +>>> if 'cat' in a: +... print "meaw" +... +meaw +>>> pets = {'cat': 1, 'dog':2, 'croc': 10} +>>> if 'croc' in pets: +... print pets['croc'] +... +10 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for} example} + \begin{lstlisting} +>>> a = ['cat', 'window', 'defenestrate'] +>>> for x in a: +... print x, len(x) +... +cat 3 +window 6 +defenestrate 12 +>>> knights = {'gallahad': 'the pure', +... 'robin': 'the brave'} +>>> for k, v in knights.iteritems(): +... print k, v +... +gallahad the pure +robin the brave +\end{lstlisting} +\end{frame} diff --git a/day1/Session-3.tex b/day1/Session-3.tex new file mode 100755 index 0000000..0e0fd96 --- /dev/null +++ b/day1/Session-3.tex @@ -0,0 +1,2745 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Tutorial slides on Python. +% +% Author: Prabhu Ramachandran <prabhu at aero.iitb.ac.in> +% Copyright (c) 2005-2008, Prabhu Ramachandran +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} +%\documentclass[draft]{beamer} +%\documentclass[compress,handout]{beamer} +%\usepackage{pgfpages} +%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] + +% Modified from: generic-ornate-15min-45min.de.tex +\mode<presentation> +{ + \usetheme{Warsaw} + \useoutertheme{split} + \setbeamercovered{transparent} +} + +\usepackage[english]{babel} +\usepackage[latin1]{inputenc} +%\usepackage{times} +\usepackage[T1]{fontenc} + +% Taken from Fernando's slides. +\usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} +\usepackage[scaled=.95]{helvet} + +\definecolor{darkgreen}{rgb}{0,0.5,0} + +\usepackage{listings} +\lstset{language=Python, + basicstyle=\ttfamily, + commentstyle=\color{red}\itshape, + stringstyle=\color{darkgreen}, + showstringspaces=false, + keywordstyle=\color{blue}\bfseries} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Macros +\setbeamercolor{emphbar}{bg=blue!20, fg=black} +\newcommand{\emphbar}[1] +{\begin{beamercolorbox}[rounded=true]{emphbar} + {#1} + \end{beamercolorbox} +} +\newcounter{time} +\setcounter{time}{0} +\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} + +\newcommand{\typ}[1]{\texttt{#1}} + +\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } + +%%% This is from Fernando's setup. +% \usepackage{color} +% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} +% % Use and configure listings package for nicely formatted code +% \usepackage{listings} +% \lstset{ +% language=Python, +% basicstyle=\small\ttfamily, +% commentstyle=\ttfamily\color{blue}, +% stringstyle=\ttfamily\color{orange}, +% showstringspaces=false, +% breaklines=true, +% postbreak = \space\dots +% } + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Basic Python]{Python:\\A great programming toolkit} + +\author[Asokan \& Prabhu] {Asokan Pichai\\Prabhu Ramachandran} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {25, July 2009} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} +%\logo{\pgfuseimage{iitmlogo}} + + +%% Delete this, if you do not want the table of contents to pop up at +%% the beginning of each subsection: +\AtBeginSubsection[] +{ + \begin{frame}<beamer> + \frametitle{Outline} + \tableofcontents[currentsection,currentsubsection] + \end{frame} +} + + +% If you wish to uncover everything in a step-wise fashion, uncomment +% the following command: +%\beamerdefaultoverlayspecification{<+->} + +%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% DOCUMENT STARTS +\begin{document} + +\begin{frame} + \titlepage +\end{frame} +\begin{frame} + {Acknowledgements} + \begin{center} + This program is conducted by\\ + IIT, Bombay\\ + through CDEEP\\as part of the open source initiatives\\ + under the aegis of\\ + \alert{National Mission on Education through ICT,} \\ + Ministry of HRD. + \end{center} +\end{frame} + +\begin{frame} + \frametitle{Outline} + \tableofcontents + % You might wish to add the option [pausesections] +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TODO +% +% * Add slide on Python packages (modules) +% * Add slides on reference counting. + +\section{Agenda} +\begin{frame}{About the Workshop} + \begin{description} + \item[Session 1] Sat 14:00--15:55 + \item[Session 2] Sat 16:05--18:00 + \item[Session 3] Sun 14:00--15:55 + \item[Session 4] Sun 16:05--18:00 + \end{description} + + \begin{block}{Goal of the workshop} + At the end of this program, successful participants will be able to use python as their scripting and problem solving language. Aimed at Engg. students--focus on basic numerics and plotting-- but should serve a similar purpose for others. + \end{block} +\end{frame} + +\begin{frame}{Checklist} + Let us verify that all of us are having the same (similar) tools and environment + \begin{description} + \item[python] Type python at the command line. Do you see version 2.5 or later? + \item[IPython] Is IPython available? + \item[Editor] Which editor? scite, vim, emacs, \ldots + \end{description} +\end{frame} + +\section{Overview} +\begin{frame}{Session 1} + \begin{itemize} + \item Introduction and motivation + \item Using the interpreter(s) + \item Basic data types: int, float, string + \item Basic data structures: list + \item Basic console IO: \texttt{raw\_input(), print} + \item Basic control flow: \texttt{if, while} + \item Problem set 1 + \item Functions $\rightarrow$ Problem set 2 + \item lists, \texttt{for} $\rightarrow$ Problem set 3 + \item IO, Modules $\rightarrow$ Problem sets 4,5, \ldots + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Introduction} + \begin{itemize} + \item Creator and BDFL: Guido van Rossum + \item Conceived in December 1989 + \item ``Python'' as in Monty Python's Flying Circus + \item Current stable version of Python is 2.6.x + \item PSF license (like BSD: no strings attached) + \item Highly cross platform + \item Runs on the Nokia series 60! + \item \alert{Philosophy:} Simple and complete by design + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Resources} + \begin{itemize} + \item Part of many GNU/Linux distributions + \item Web: \url{http://www.python.org} + \item Doc: \url{http://www.python.org/doc} + \item Free Tutorials: + \begin{itemize} + \item Official Python tutorial: \url{http://docs.python.org/tut/tut.html} + \item Byte of Python: \url{http://www.byteofpython.info/} + \item Dive into Python: \url{http://diveintopython.org/} + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Why Python?} + \begin{itemize} + \item Designed to be readable and easy to use + \item High level, interpreted, modular, OO + \item Much faster development cycle + \item Powerful interactive environment + \item Rapid application development + \item Rich standard library and modules + \item Interfaces well with C++, C and FORTRAN + \item \alert{More than a math package $\Rightarrow$ some extra work compared to math packages} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Use cases} + \begin{itemize} + \item NASA: Space Shuttle Mission Design + \item AstraZeneca: Collaborative Drug Discovery + \item ForecastWatch.com: Helps Meteorologists + \item Industrial Light \& Magic: Runs on Python + \item Zope: Commercial grade Toolkit + \item Plone: Professional high feature CMS + \item RedHat: install scripts, sys-admin tools + \item Django: A great web application framework + \item Google: A strong python shop + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{To sum up, python is\ldots} + \begin{itemize} + \item dynamically typed, interpreted $\rightarrow$ rapid testing/prototyping + \item powerful, very high level + \item has full introspection + \item Did we mention powerful? + \end{itemize} + \begin{block}{But \ldots} + may be wanting in performance. specialised resources such as SWIG, \alert{Cython} are available + \end{block} + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 15m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\section{Python} + +\subsection{Getting Started} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> print 'Hello Python' +>>> print 3124 * 126789 +>>> 1786 % 12 +>>> 3124 * 126789 +>>> a = 3124 * 126789 +>>> big = 12345678901234567890 ** 3 +>>> verybig = big * big * big * big +>>> 12345**6, 12345**67, 12345**678 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> s = 'Hello ' +>>> p = 'World' +>>> s + p +>>> s * 12 +>>> s * s +>>> s + p * 12, (s + p)* 12 +>>> s * 12 + p * 12 +>>> 12 * s + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> 17/2 +>>> 17/2.0 +>>> 17.0/2 +>>> 17.0/8.5 +>>> int(17/2.0) +>>> float(17/2) +>>> str(17/2.0) +>>> round( 7.5 ) + \end{lstlisting} + \begin{block}{Mini exercise} + Round a float to the nearest integer, using \texttt{int()}? + \end{block} +\end{frame} + +\begin{frame}{Midi exercises} + \begin{center} + \begin{itemize} + \item What does this do? + \item \texttt{round(amount * 10) /10.0 } + \end{itemize} + \end{center} +\end{frame} + +\begin{frame}{More exercises?} + \begin{center} + \begin{block}{Round sums} + How to round a number to the nearest 5 paise?\\ + \begin{description} + \item[Remember] 17.23 $\rightarrow$ 17.25,\\ while 17.22 $\rightarrow$ 17.20\\ + \end{description} + How to round a number to the nearest 20 paise? + \end{block} + \end{center} +\end{frame} + +\begin{frame}[fragile] {A question of good style} + \begin{lstlisting} + amount = 12.68 + denom = 0.05 + nCoins = round(amount/denom) + rAmount = nCoins * denom + \end{lstlisting} + \pause + \begin{block}{Style Rule \#1} + Naming is 80\% of programming + \end{block} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item Case sensitive + \item Dynamically typed $\Rightarrow$ need not specify a type + \begin{lstlisting} +a = 1 +a = 1.1 +a = "Now I am a string!" + \end{lstlisting} + \item Comments: + \begin{lstlisting} +a = 1 # In-line comments +# Comment in a line to itself. +a = "# This is not a comment!" + \end{lstlisting} + \end{itemize} + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 30m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Data types} +\begin{frame} + \frametitle{Basic types} + \begin{itemize} + \item numbers: float, int, long, complex + \item strings + \item boolean + \end{itemize} + \begin{block}{Also to be discussed later} + tuples, lists, dictionaries, functions, objects\ldots + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Numbers} + \vspace*{-0.25in} + \begin{lstlisting} +>>> a = 1 # Int. +>>> l = 1000000L # Long +>>> e = 1.01325e5 # float +>>> f = 3.14159 # float +>>> c = 1+1j # Complex! +>>> print f*c/a +(3.14159+3.14159j) +>>> print c.real, c.imag +1.0 1.0 +>>> abs(c) +1.4142135623730951 +>>> abs( 8 - 9.5 ) +1.5 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Boolean} + \begin{lstlisting} +>>> t = True +>>> f = not t +False +>>> f or t +True +>>> f and t +False + \end{lstlisting} + \begin{block}{Try:} + NOT True\\ + not TRUE + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Relational and logical operators} + \begin{lstlisting} +>>> a, b, c = -1, 0, 1 +>>> a == b +False +>>> a <= b +True +>>> a + b != c +True +>>> a < b < c +True +>>> c >= a + b +True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Strings} + \begin{lstlisting} +s = 'this is a string' +s = 'This one has "quotes" inside!' +s = "I have 'single-quotes' inside!" +l = "A string spanning many lines\ +one more line\ +yet another" +t = """A triple quoted string does +not need to be escaped at the end and +"can have nested quotes" etc.""" + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More Strings} + \vspace*{-0.2in} + \begin{lstlisting} +>>> w = "hello" +>>> print w[0] + w[2] + w[-1] +hlo +>>> len(w) # guess what +5 +>>> s = u'Unicode strings!' +>>> # Raw strings (note the leading 'r') +... r_s = r'A string $\alpha \nu$' + \end{lstlisting} +\pause + \begin{lstlisting} +>>> w[0] = 'H' # Can't do that! +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: object does not support item assignment + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Let us switch to IPython} + Why? + \begin{block} + {Better help (and a lot more)} + Tab completion\\ + ?\\ + .?\\ + object.function? + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More on strings} + \begin{lstlisting} +In [1]: a = 'hello world' +In [2]: a.startswith('hell') +Out[2]: True +In [3]: a.endswith('ld') +Out[3]: True +In [4]: a.upper() +Out[4]: 'HELLO WORLD' +In [5]: a.upper().lower() +Out[5]: 'hello world' + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Still with strings} + \begin{lstlisting} +In [6]: a.split() +Out[6]: ['hello', 'world'] +In [7]: ''.join(['a', 'b', 'c']) +Out[7]: 'abc' +In [8] 'd' in ''.join( 'a', 'b', 'c') +Out[8]: False + \end{lstlisting} + \begin{block}{Try:} + \texttt{a.split( 'o' )}\\ + \texttt{'x'.join( a.split( 'o' ) )} + \end{block} +\end{frame} + +\begin{frame}[fragile]{Surprise! strings!!} + \begin{lstlisting} +In [11]: x, y = 1, 1.2 +In [12]: 'x is %s, y is %s' %(x, y) +Out[12]: 'x is 1, y is 1.234' + \end{lstlisting} + \begin{block}{Try:} + \texttt{'x is \%d, y is \%f' \%(x, y) }\\ + \texttt{'x is \%3d, y is \%4.2f' \%(x, y) } + \end{block} + \small +\url{docs.python.org/lib/typesseq-strings.html}\\ +\end{frame} + +\begin{frame} + {Interlude} + \begin{block} + {A classic problem} + How to interchange values of two variables? Please note that the type of either variable is unknown and it is not necessary that both be of the same type even! + \end{block} + \inctime{30} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 25 m+ Interlude break 5 mins, running 60m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Control flow} +\begin{frame} + \frametitle{Control flow constructs} + \begin{itemize} + \item \kwrd{if/elif/else}: branching + \item \kwrd{while}: looping + \item \kwrd{for}: iterating + \item \kwrd{break, continue}: modify loop + \item \kwrd{pass}: syntactic filler + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic conditional flow} + \begin{lstlisting} +In [21]: a = 7 +In [22]: b = 8 +In [23]: if a > b: + ....: print 'Hello' + ....: else: + ....: print 'World' + ....: + ....: +World + \end{lstlisting} + Let us switch to creating a file +\end{frame} + +\begin{frame} + {Creating python files} + \begin{itemize} + \item aka scripts + \item use your editor + \item Note that white space is the way to specify blocks! + \item extension \typ{.py} + \item run with \texttt{python hello.py} at the command line + \item in IPython\ldots + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{If...elif...else} example} +\begin{lstlisting} +x = int(raw_input("Enter an integer:")) +if x < 0: + print 'Be positive!' +elif x == 0: + print 'Zero' +elif x == 1: + print 'Single' +else: + print 'More' +\end{lstlisting} +\end{frame} + +\begin{frame}{Simple IO} + \begin{block} + {Console Input} + \texttt{raw\_input(}) waits for user input.\\Prompt string is optional.\\ + All keystrokes are Strings!\\\texttt{int()} converts string to int. + \end{block} + \begin{block} + {Console output} + \texttt{print} is straight forward. Major point to remember is the distinction between \texttt{print x} and \texttt{print x,} + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic looping} + \begin{lstlisting} +# Fibonacci series: +# the sum of two elements +# defines the next +a, b = 0, 1 +while b < 10: + print b, + a, b = b, a + b + +\end{lstlisting} +\typ{1 1 2 3 5 8}\\ +\alert{Recall it is easy to write infinite loops with \kwrd{while}} + \inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 80m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + \frametitle{Problem set 1} + \begin{itemize} + \item All the problems can be\\ + solved using \kwrd{if} and \kwrd{while} + \end{itemize} +\end{frame} + +\begin{frame}{Problem 1.1} + Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ +These are called $Armstrong$ numbers. +\end{frame} + +\begin{frame}{Problem 1.2 - Collatz sequence} +\begin{enumerate} + \item Start with an arbitrary (positive) integer. + \item If the number is even, divide by 2; if the number is odd multiply by 3 and add 1. + \item Repeat the procedure with the new number. + \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. +\end{enumerate} + Write a program that accepts the starting value and prints out the Collatz sequence. + +\end{frame} + +\begin{frame}{Problem 1.3 - Kaprekar's constant} + \begin{enumerate} + \item Take a four digit number--with at least two digits different. + \item Arrange the digits in ascending and descending order, giving A and D respectively. + \item Leave leading zeros in A! + \item Subtract A from D. + \item With the result, repeat from step 2. + \end{enumerate} + Write a program to accept a 4-digit number and display the progression to Kaprekar's constant. +\end{frame} + +\begin{frame}[fragile]{Problem 1.4} + Write a program that prints the following pyramid on the screen. + \begin{lstlisting} +1 +2 2 +3 3 3 +4 4 4 4 + \end{lstlisting} +The number of lines must be obtained from the user as input.\\ +\pause +When can your code fail? +\only<2->{\inctime{25}} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 25 m, running 105m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Functions} +\begin{frame}[fragile] +\frametitle{Functions: examples} + \begin{lstlisting} +def signum( r ): + """returns 0 if r is zero + -1 if r is negative + +1 if r is positive""" + if r < 0: + return -1 + elif r > 0: + return 1 + else: + return 0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: examples} + \begin{lstlisting} +def pad( n, size ): + """pads integer n with spaces + into a string of length size + """ + SPACE = ' ' + s = str( n ) + padSize = size - len( s ) + return padSize * SPACE + s + \end{lstlisting} +\pause +What about \%3d? +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} + \begin{lstlisting} +def what( n ): + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} +\begin{lstlisting} +def what( n ): + i = 1 + while i * i < n: + i += 1 + return i * i == n, i + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} + \begin{lstlisting} +def what( n, x ): + z = 1.0 + if n < 0: + x = 1.0 / x + n = -n + while n > 0: + if n % 2 == 1: + z *= x + n /= 2 + x *= x + return z + \end{lstlisting} +\end{frame} + +\begin{frame} + {Before writing a function} + \begin{itemize} + \item Builtin functions for various and sundry + \item \typ{abs, any, all, len, max, min} + \item \typ{pow, range, sum, type} + \item Refer here: + \url{http://docs.python.org/library/functions.html} + \end{itemize} + \inctime{15} +\end{frame} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 120m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame}{Problem set 2} + The focus is on writing functions and calling them. +\end{frame} + +\begin{frame}{Problem 2.1} + Write a function to return the gcd of two numbers. +\end{frame} + +\begin{frame}{Problem 2.2} +A pythagorean triad $(a,b,c)$ has the property $a^2 + b^2 = c^2$.\\By primitive we mean triads that do not `depend' on others. For example, (4,3,5) is a variant of (3,4,5) and hence is not primitive. And (10,24,26) is easily derived from (5,12,13) and should not be displayed by our program. \\ +Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100 +\end{frame} + +\begin{frame}{Problem 2.3} + Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\\For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square). +\end{frame} + +\begin{frame}{Problem 2.4} + The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. For example, the aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.\\ + Write a function that returns the aliquot number of a given number. +\end{frame} + +\begin{frame}{Problem 2.5} + A pair of numbers (a, b) is said to be \alert{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ + Example: \texttt{220, 284}\\ + Write a program that prints all five digit amicable pairs. + \inctime{30} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 30 m, running 150m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Lists} + +\begin{frame}[fragile] + \frametitle{List creation and indexing} +\begin{lstlisting} +>>> a = [] # An empty list. +>>> a = [1, 2, 3, 4] # More useful. +>>> len(a) +4 +>>> a[0] + a[1] + a[2] + a[-1] +10 +\end{lstlisting} + \begin{itemize} + \item Indices start with ? + \item Negative indices indicate ? + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: slices} + \begin{itemize} + \item Slicing is a basic operation + \item \typ{list[initial:final:step]} + \item The step is optional + \end{itemize} +\begin{lstlisting} +>>> a[1:3] # A slice. +[2, 3] +>>> a[1:-1] +[2, 3, 4] +>>> a[1:] == a[1:-1] +False +\end{lstlisting} +Explain last result +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: more slices} +\begin{lstlisting} +>>> a[0:-1:2] # Notice the step! +[1, 3] +>>> a[::2] +[1, 3] +>>> a[-1::-1] +\end{lstlisting} +What do you think the last one will do? + \emphbar{Note: Strings also use same indexing and slicing.} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: examples} +\begin{lstlisting} +>>> a = [1, 2, 3, 4] +>>> a[:2] +[1, 3] +>>> a[0:-1:2] +[1, 3] +\end{lstlisting} +\pause +\alert{Lists are mutable (unlike strings)} +\begin{lstlisting} +>>> a[1] = 20 +>>> a +[1, 20, 3, 4] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists are mutable and heterogenous} +\begin{lstlisting} +>>> a = ['spam', 'eggs', 100, 1234] +>>> a[2] = a[2] + 23 +>>> a +['spam', 'eggs', 123, 1234] +>>> a[0:2] = [1, 12] # Replace items +>>> a +[1, 12, 123, 1234] +>>> a[0:2] = [] # Remove items +>>> a.append( 12345 ) +>>> a +[123, 1234, 12345] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List methods} +\begin{lstlisting} +>>> a = ['spam', 'eggs', 1, 12] +>>> a.reverse() # in situ +>>> a +[12, 1, 'eggs', 'spam'] +>>> a.append(['x', 1]) +>>> a +[12, 1, 'eggs', 'spam', ['x', 1]] +>>> a.extend([1,2]) # Extend the list. +>>> a.remove( 'spam' ) +>>> a +[12, 1, 'eggs', ['x', 1], 1, 2] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List containership} + \begin{lstlisting} +>>> a = ['cat', 'dog', 'rat', 'croc'] +>>> 'dog' in a +True +>>> 'snake' in a +False +>>> 'snake' not in a +True +>>> 'ell' in 'hello world' +True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Tuples: immutable} +\begin{lstlisting} +>>> t = (0, 1, 2) +>>> print t[0], t[1], t[2], t[-1] +0 1 2 2 +>>> t[0] = 1 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: object does not support item + assignment +\end{lstlisting} +\begin{itemize} + \item Multiple return values are actually a tuple. + \item Exchange is tuple (un)packing +\end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{range()} function} + \begin{lstlisting} +>>> range(7) +[0, 1, 2, 3, 4, 5, 6] +>>> range( 3, 9) +[3, 4, 5, 6, 7, 8] +>>> range( 4, 17, 3) +[4, 7, 10, 13, 16] +>>> range( 5, 1, -1) +[5, 4, 3, 2] +>>> range( 8, 12, -1) +[] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for\ldots range(\ldots)} idiom} + \begin{lstlisting} +In [83]: for i in range(5): + ....: print i, i * i + ....: + ....: +0 0 +1 1 +2 4 +3 9 +4 16 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for}: the list companion} + + \begin{lstlisting} +In [84]: a = ['a', 'b', 'c'] +In [85]: for x in a: + ....: print x, chr( ord(x) + 10 ) + ....: +a k +b l +c m + \end{lstlisting} + Iterating over the list and not the index + reference\\ + what if you want the index? +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for}: the list companion} + \begin{lstlisting} +In [89]: for p, ch in enumerate( a ): + ....: print p, ch + ....: + ....: +0 a +1 b +2 c + \end{lstlisting} +Try: \typ{print enumerate(a)} +\inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 170m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + {Problem set 3} + As you can guess, idea is to use \kwrd{for}! +\end{frame} + +\begin{frame}{Problem 3.1} + Which of the earlier problems is simpler when we use \kwrd{for} instead of \kwrd{while}? +\end{frame} + +\begin{frame}{Problem 3.2} + Given an empty chessboard and one Bishop placed in any square, say (r, c), generate the list of all squares the Bishop could move to. +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.3} + + Given two real numbers \typ{a, b}, and an integer \typ{N}, write a + function named \typ{linspace( a, b, N)} that returns an ordered list + of \typ{N} points starting with \typ{a} and ending in \typ{b} and + equally spaced.\\ + + For example, \typ{linspace(0, 5, 11)}, should return, \\ +\begin{lstlisting} +[ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, + 3.0 , 3.5, 4.0 , 4.5, 5.0 ] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.4a (optional)} + +Use the \typ{linspace} function and generate a list of N tuples of the form\\ +\typ{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions,\begin{itemize} + \item \typ{f(x) = sin(x)} + \item \typ{f(x) = sin(x) + sin(10*x)}. +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.4b (optional)} + + Using the tuples generated earlier, determine the intervals where the roots of the functions lie. + + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 185m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{IO} + +\begin{frame}[fragile] + \frametitle{Simple tokenizing and parsing} + \begin{lstlisting} +s = """The quick brown fox jumped + over the lazy dog""" +for word in s.split(): + print word.capitalize() + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 4.1} + Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \\ + \begin{lstlisting} + [1,3,4,5,6,7,12,15,18,19,20,21] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File handling} +\begin{lstlisting} +>>> f = open('/path/to/file_name') +>>> data = f.read() # Read entire file. +>>> line = f.readline() # Read one line. +>>> f.close() # close the file. +\end{lstlisting} +Writing files +\begin{lstlisting} +>>> f = open('/path/to/file_name', 'w') +>>> f.write('hello world\n') +>>> f.close() +\end{lstlisting} +\begin{itemize} + \item Everything read or written is a string +\end{itemize} +\emphbar{Try \typ{file?} for more help} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File and \kwrd{for}} +\begin{lstlisting} +>>> f = open('/path/to/file_name') +>>> for line in f: +... print line +... +\end{lstlisting} +\end{frame} + +\begin{frame}{Problem 4.2} + The given file has lakhs of records in the form:\\ + \typ{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}\\ + Some entries may be empty. Read the data from this file and print the + name of the student with the maximum total marks. +\end{frame} + +\begin{frame}{Problem 4.3} + For the same data file compute the average marks in different + subjects, the student with the maximum mark in each subject and also + the standard deviation of the marks. Do this efficiently. + + \inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 205m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Modules} + +\begin{frame}[fragile] + {Modules} +\begin{lstlisting} +>>> sqrt(2) +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +NameError: name 'sqrt' is not defined +>>> import math +>>> math.sqrt(2) +1.4142135623730951 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {Modules} + \begin{itemize} + \item The \kwrd{import} keyword ``loads'' a module + \item One can also use: + \begin{lstlisting} +>>> from math import sqrt +>>> from math import * + \end{lstlisting} + \item What is the difference? + \item \alert{Use the later only in interactive mode} + \end{itemize} + \emphbar{Package hierarchies} + \begin{lstlisting} +>>> from os.path import exists + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Modules: Standard library} + \begin{itemize} + \item Very powerful, ``Batteries included'' + \item Some standard modules: + \begin{itemize} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib2}, \typ{smtplib} + \item System, Command line arguments: \typ{sys} + \item Operating system interface: \typ{os} + \item Regular expressions: \typ{re} + \item Compression: \typ{gzip}, \typ{zipfile}, and \typ{tarfile} + \item And a whole lot more! + \end{itemize} + \item Check out the Python Library reference: + \url{http://docs.python.org/library/} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + {Modules of special interest} + \begin{description}[matplotlibfor2d] + + \item[\typ{numpy}] Efficient, powerful numeric arrays + + \item[\typ{matplotlib}] Easy, interactive, 2D plotting + + \item[\typ{scipy}] statistics, optimization, integration, linear + algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + + \item[Mayavi] Easy, interactive, 3D plotting + + \end{description} +\end{frame} + +\begin{frame}[fragile] + {Creating your own modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \typ{.py} extension + \item This file becomes a module! + \item Accessible when in the current directory + \item Use \typ{cd} in IPython to change directory + + \item Naming your module + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- arith.py --- +def gcd(a, b): + if a%b == 0: return b + return gcd(b, a%b) +def lcm(a, b): + return a*b/gcd(a, b) +# ------------------ +>>> import arith +>>> arith.gcd(26, 65) +13 +>>> arith.lcm(26, 65) +130 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 5.1} + + Put all the functions you have written so far as part of the problems + into one module called \typ{iitb.py} and use this module from IPython. + +\inctime{20} +\end{frame} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 225m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + \frametitle{Did we meet the goal?} + \tableofcontents + % You might wish to add the option [pausesections] + \end{frame} + + \begin{frame} + {Tomorrow} + \begin{itemize} + \item Plotting: 2D, 3D + \item NumPy, SciPy + \item Dictionary, Set + \item Debugging + \item Testing + \item \ldots + \end{itemize} + 11:30--13:00 Discussion of answers to problems OPTIONAL + \end{frame} +\end{document} + + +\begin{frame}[fragile] + \frametitle{More on functions} + \begin{itemize} + \item Support default and keyword arguments + \item Scope of variables in the function is local + \item Mutable items are \alert{passed by reference} + \item First line after definition may be a documentation string + (\alert{recommended!}) + \item Function definition and execution defines a name bound to the + function + \item You \emph{can} assign a variable to a function! + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Functions: default arguments} + \begin{lstlisting} +def ask_ok(prompt, retries=4, complaint='Yes or no!'): + while True: + ok = raw_input(prompt) + if ok in ('y', 'ye', 'yes'): + return True + if ok in ('n', 'no', 'nop', 'nope'): + return False + retries = retries - 1 + if retries < 0: + raise IOError, 'bad user' + print complaint + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: keyword arguments} + \begin{lstlisting} +def parrot(voltage, state='a stiff', + action='voom', type='Norwegian Blue'): + print "-- This parrot wouldn't", action, + print "if you put", voltage, "Volts through it." + print "-- Lovely plumage, the", type + print "-- It's", state, "!" + +parrot(1000) +parrot(action = 'VOOOOOM', voltage = 1000000) +parrot('a thousand', state = 'pushing up the daisies') +parrot('a million', 'bereft of life', 'jump') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: arbitrary argument lists} + \begin{itemize} + \item Arbitrary number of arguments using \verb+*args+ or + \verb+*whatever+ + \item Keyword arguments using \verb+**kw+ + \item Given a tuple/dict how do you call a function? + \begin{itemize} + \item Using argument unpacking + \item For positional arguments: \verb+foo(*[5, 10])+ + \item For keyword args: \verb+foo(**{'a':5, 'b':10})+ + \end{itemize} + \end{itemize} +\begin{lstlisting} +def foo(a=10, b=100): + print a, b +def func(*args, **keyword): + print args, keyword +# Unpacking: +args = [5, 10] +foo(*args) +kw = {'a':5, 'b':10} +foo(**kw) +\end{lstlisting} +\end{frame} + +\subsection{Modules, exceptions, classes} + +\begin{frame} + \frametitle{Modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \typ{.py} extension + \item This file becomes a module! + \item Modules are searched in the following: + \begin{itemize} + \item Current directory + \item Standard: \typ{/usr/lib/python2.3/site-packages/} etc. + \item Directories specified in PYTHONPATH + \item \typ{sys.path}: current path settings (from the \typ{sys} + module) + \end{itemize} + \item The \typ{import} keyword ``loads'' a module + \item One can also use: + \mbox{\typ{from module import name1, name2, name2}}\\ + where \typ{name1} etc. are names in the module, ``module'' + \item \typ{from module import *} \ --- imports everything from module, + \alert{use only in interactive mode} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- foo.py --- +some_var = 1 +def fib(n): # write Fibonacci series up to n + """Print a Fibonacci series up to n.""" + a, b = 0, 1 + while b < n: + print b, + a, b = b, a+b +# EOF + +>>> import foo +>>> foo.fib(10) +1 1 2 3 5 8 +>>> foo.some_var +1 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Namespaces} + \begin{itemize} + \item A mapping from names to objects + \item Modules introduce a namespace + \item So do classes + \item The running script's namespace is \verb+__main__+ + \item A modules namespace is identified by its name + \item The standard functions (like \typ{len}) are in the + \verb+__builtin__+ namespace + \item Namespaces help organize different names and their bindings to + different objects + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Exceptions} + \begin{itemize} + \item Python's way of notifying you of errors + \item Several standard exceptions: \typ{SyntaxError}, \typ{IOError} + etc. + \item Users can also \typ{raise} errors + \item Users can create their own exceptions + \item Exceptions can be ``caught'' via \typ{try/except} blocks + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exception: examples} +\begin{lstlisting} +>>> 10 * (1/0) +Traceback (most recent call last): + File "<stdin>", line 1, in ? +ZeroDivisionError: integer division or modulo by zero +>>> 4 + spam*3 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +NameError: name 'spam' is not defined +>>> '2' + 2 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: cannot concatenate 'str' and 'int' objects +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exception: examples} +\begin{lstlisting} +>>> while True: +... try: +... x = int(raw_input("Enter a number: ")) +... break +... except ValueError: +... print "Invalid number, try again..." +... +>>> # To raise exceptions +... raise ValueError, "your error message" +Traceback (most recent call last): + File "<stdin>", line 2, in ? +ValueError: your error message +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: the big picture} + \begin{itemize} + \item Lets you create new data types + \item Class is a template for an object belonging to that class + \item Note: in Python a class is also an object + \item Instantiating a class creates an instance (an object) + \item An instance encapsulates the state (data) and behavior + (methods) + \item Allows you to define an inheritance hierarchy + \begin{itemize} + \item ``A Honda car \alert{is a} car.'' + \item ``A car \alert{is an} automobile.'' + \item ``A Python \alert{is a} reptile.'' + \end{itemize} + \item Programmers need to think OO + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: what's the big deal?} + \begin{itemize} + \item Lets you create objects that mimic a real problem being + simulated + \item Makes problem solving more natural and elegant + \item Easier to create code + \item Allows for code-reuse + \item Polymorphism + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Class definition and instantiation} + \begin{itemize} + \item Class definitions when executed create class objects + \item Instantiating the class object creates an instance of the + class + \end{itemize} +\footnotesize +\begin{lstlisting} +class Foo(object): + pass +# class object created. +# Create an instance of Foo. +f = Foo() +# Can assign an attribute to the instance +f.a = 100 +print f.a +100 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes \ldots} + \begin{itemize} + \item All attributes are accessed via the \typ{object.attribute} + syntax + \item Both class and instance attributes are supported + \item \emph{Methods} represent the behavior of an object: crudely + think of them as functions ``belonging'' to the object + \item All methods in Python are ``virtual'' + \item Inheritance through subclassing + \item Multiple inheritance is supported + \item No special public and private attributes: only good + conventions + \begin{itemize} + \item \verb+object.public()+: public + \item \verb+object._private()+ \& \verb+object.__priv()+: + non-public + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: examples} +\begin{lstlisting} +class MyClass(object): + """Example class (this is the class docstring).""" + i = 12345 # A class attribute + def f(self): + """This is the method docstring""" + return 'hello world' + +>>> a = MyClass() # creates an instance +>>> a.f() +'hello world' +>>> # a.f() is equivalent to MyClass.f(a) +... # This also explains why f has a 'self' argument. +... MyClass.f(a) +'hello world' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes (continued)} + \begin{itemize} + \item \typ{self} is \alert{conventionally} the first argument for a + method + \item In previous example, \typ{a.f} is a method object + \item When \typ{a.f} is called, it is passed the instance \typ{a} as + the first argument + \item If a method called \verb+__init__+ exists, it is called when + the object is created + \item If a method called \verb+__del__+ exists, it is called before + the object is garbage collected + \item Instance attributes are set by simply ``setting'' them in + \typ{self} + \item Other special methods (by convention) like \verb+__add__+ let + you define numeric types: + {\footnotesize \url{http://docs.python.org/ref/specialnames.html} + \\ \url{http://docs.python.org/ref/numeric-types.html} + } + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: examples} +\begin{lstlisting} +class Bag(MyClass): # Shows how to derive classes + def __init__(self): # called on object creation. + self.data = [] # an instance attribute + def add(self, x): + self.data.append(x) + def addtwice(self, x): + self.add(x) + self.add(x) +>>> a = Bag() +>>> a.f() # Inherited method +'hello world' +>>> a.add(1); a.addtwice(2) +>>> a.data +[1, 2, 2] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Derived classes} + \begin{itemize} + \item Call the parent's \verb+__init__+ if needed + \item If you don't need a new constructor, no need to define it in subclass + \item Can also use the \verb+super+ built-in function + \end{itemize} +\begin{lstlisting} +class AnotherBag(Bag): + def __init__(self): + # Must call parent's __init__ explicitly + Bag.__init__(self) + # Alternatively use this: + super(AnotherBag, self).__init__() + # Now setup any more data. + self.more_data = [] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: polymorphism} +\begin{lstlisting} +class Drawable(object): + def draw(self): + # Just a specification. + pass +\end{lstlisting} +\mode<presentation>{\pause} +\begin{lstlisting} +class Square(Drawable): + def draw(self): + # draw a square. +class Circle(Drawable): + def draw(self): + # draw a circle. +\end{lstlisting} +\mode<presentation>{\pause} +\begin{lstlisting} +class Artist(Drawable): + def draw(self): + for obj in self.drawables: + obj.draw() +\end{lstlisting} +\end{frame} + +\subsection{Miscellaneous} + +\begin{frame}[fragile] + \frametitle{Stand-alone scripts} +Consider a file \typ{f.py}: +\begin{lstlisting} +#!/usr/bin/env python +"""Module level documentation.""" +# First line tells the shell that it should use Python +# to interpret the code in the file. +def f(): + print "f" + +# Check if we are running standalone or as module. +# When imported, __name__ will not be '__main__' +if __name__ == '__main__': + # This is not executed when f.py is imported. + f() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List comprehensions} +\begin{lstlisting} +>>> veg = ['tomato', 'cabbage', 'carrot', 'potato'] +>>> [x.upper() for x in veg] +['TOMATO', 'CABBAGE', 'CARROT', 'POTATO'] +>>> vec = range(0, 8) +>>> even = [x for x in vec if x%2 == 0] +>>> even +[0, 2, 4, 6] +>>> [x*x for x in even] +[0, 4, 16, 36] +>>> odd = [x for x in vec if x%2 == 1] +>>> odd +[1, 3, 5, 7] +>>> [x*y for x in even for y in odd] +[0, 0, 0, 0, 2, 6, 10, 14, 4, 12, 20, 28, 6, 18,30,42] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features} + \begin{itemize} + \item Input and output caching: + \begin{itemize} + \item \verb+In+: a list of all entered input + \item \verb+Out+: a dict of all output + \item \verb+_+, \verb+__+, \verb+__+ are the last three results as + is \verb+_N+ + \item \verb+%hist [-n]+ macro shows previous history, \verb+-n+ + suppresses line number information + \end{itemize} + \item Log the session using \verb+%logstart+, \verb+%logon+ and + \verb+%logoff+ + \item \verb+%run [options] file[.py]+ -- running Python code + \begin{itemize} + \item \verb+%run -d [-b<N>]+: debug script with pdb + \verb+N+ is the line number to break at (defaults to 1) + \item \verb+%run -t+: time the script + \item \verb+%run -p+: Profile the script + \end{itemize} + \item \verb+%prun+ runs a statement/expression under the profiler + \item \verb+%macro [options] macro_name n1-n2 n3-n4 n6+ save specified + lines to a macro with name \verb+macro_name+ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features \ldots} + \begin{itemize} + \item \verb+%edit [options] [args]+: edit lines of code or file + specified in editor (configure editor via \verb+$EDITOR+) + \item \verb+%cd+ changes directory, see also \verb+%pushd, %popd, %dhist+ + \item Shell access + \begin{itemize} + \item \verb+!command+ runs a shell command and returns its output + \item \verb+files = %sx ls+ or \verb+files = !ls+ sets + \verb+files+ to all result of the \verb+ls+ command + \item \verb+%sx+ is quiet + \item \verb+!ls $files+ passes the \verb+files+ variable to the + shell command + \item \verb+%alias alias_name cmd+ creates an alias for a system + command + \end{itemize} + \item \verb+%colors+ lets you change the color scheme to + \verb+NoColor, Linux, LightBG+ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features \ldots} + \begin{itemize} + \item Use \verb+;+ at the end of a statement to suppress printing + output + \item \verb+%bookmark+: store a bookmarked location, for use with \verb+%cd+ + \item \verb+%who, %whos+: print information on variables + \item \verb+%save [options] filename n1-n2 n3-n4+: save lines to a + file + \item \verb+%time statement+: Time execution of a Python statement or + expression + \item \verb+%timeit [-n<N> -r<R> [-t|-c]] statement+: time execution + using Python's timeit module + \item Can define and use profiles to setup IPython differently: + \verb+math, scipy, numeric, pysh+ etc. + \item \verb+%magic+: \alert{Show help on all magics} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File handling} +\begin{lstlisting} +>>> # Reading files: +... f = open('/path/to/file_name') +>>> data = f.read() # Read entire file. +>>> line = f.readline() # Read one line. +>>> # Read entire file appending each line into a list +... lines = f.readlines() +>>> f.close() # close the file. +>>> # Writing files: +... f = open('/path/to/file_name', 'w') +>>> f.write('hello world\n') +\end{lstlisting} + \begin{itemize} + \item \typ{tell()}: returns int of current position + \item \typ{seek(pos)}: moves current position to specified byte + \item Call \typ{close()} when done using a file + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Math} + \begin{itemize} + \item \typ{math} module provides basic math routines for + floats + \item \typ{cmath} module provides math routies for complex + numbers + \item \typ{random}: provides pseudo-random number generators + for various distributions + \item These are always available and part of the standard library + \item More serious math is provided by the NumPy/SciPy modules -- + these are not standard and need to be installed separately + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Timing and profiling} + \begin{itemize} + \item Timing code: use the \typ{time} module + \item Read up on \typ{time.time()} and \typ{time.clock()} + \item \typ{timeit}: is a better way of doing timing + \item IPython has handy \typ{time} and \typ{timeit} macros (type + \typ{timeit?} for help) + \item IPython lets you debug and profile code via the \typ{run} + macro (type \typ{run?} on the prompt to learn more) + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item \typ{dir([object])} function: attributes of given object + \item \typ{type(object)}: returns type information + \item \typ{str(), repr()}: convert object to string representation + \item \typ{isinstance, issubclass} + \item \typ{assert} statements let you do debugging assertions in + code + \item \typ{csv} module: reading and writing CSV files + \item \typ{pickle}: lets you save and load Python objects + (\alert{serialization}) + \item \typ{sys.argv}: command line arguments + \item \typ{os.path}: common path manipulations + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Test driven development (TDD)} + \begin{itemize} + \item Why? + \begin{itemize} + + \item Forces you to write reusable code! + + \item Think about the API + + \item More robust + + \item Makes refactoring very easy + + \end{itemize} + \item How? Python offers three major ways of doing this + \begin{itemize} + \item doctest + \item unittest + \item nosetest (and similar like py.test) + \end{itemize} + + \item Test every piece of functionality you offer + + \item This isn't a formal introduction but more a practical one + + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Unit test} +\begin{lstlisting} +import unittest + +class MyTestCase(unittest.TestCase): + def setUp(self): + # Called *before* each test_* + def tearDown(self): + # Called *after* each test_* + def test_something(self): + "docstring" + # Test code. + self.assertEqual(x, y) + self.assertRaises(ValueError, func, arg1, arg2 ...) + +if __name__ == '__main__': + unittest.main() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Nosetest} +\begin{lstlisting} +import particle +def test_particle(): + # Use asserts here. + p = particle.Particle(1.0) + assert p.property[0] == 1.0 + assert p.property[2] == 0.0 + +if __name__ == '__main__': + import nose + nose.main() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Testing} + \begin{itemize} + \item More details: see library reference and search for nosetest + \end{itemize} +\end{frame} + +\section{Numerics \& Plotting} + +\subsection{NumPy Arrays} + +\newcommand{\num}{\texttt{numpy}} + +\begin{frame} + \frametitle{The \num\ module} + \begin{itemize} + \item Manipulating large Python lists for scientific computing is + \alert{slow} + \item Most complex computations can be reduced to a few standard + operations + \item The \num\ module provides: + \begin{itemize} + \item An efficient and powerful array type for various common data + types + \item Abstracts out the most commonly used standard operations on + arrays + \end{itemize} + \item Numeric was the first, then came \texttt{numarray}. + \texttt{numpy} is the latest and is the future + \item This course uses \num\ and only covers the absolute basics + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Basic concepts} + \begin{itemize} + \item \num\ arrays are of a fixed size (\typ{arr.size}) and have the + same type (\typ{arr.dtype}) + \item \num\ arrays may have arbitrary dimensionality + \item The \typ{shape} of an array is the extent (length) of the + array along each dimension + \item The \typ{rank(arr)} of an array is the ``dimensionality'' of the + array + \item The \typ{arr.itemsize} is the number of bytes (8-bits) used for + each element of the array + \item \alert{Note:} The \typ{shape} and \typ{rank} may change as + long as the \typ{size} of the array is fixed + \item \alert{Note:} \typ{len(arr) != arr.size} in general + \item \alert{Note:} By default array operations are performed + \alert{elementwise} + \item Indices start from 0 + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Examples of \num} +\begin{lstlisting} +# Simple array math example +>>> from numpy import * +>>> a = array([1,2,3,4]) +>>> b = array([2,3,4,5]) +>>> a + b # Element wise addition! +array([3, 5, 7, 9]) + +>>> print pi, e # Pi and e are defined. +3.14159265359 2.71828182846 +# Create array from 0 to 10 +>>> x = arange(0.0, 10.0, 0.05) +>>> x *= 2*pi/10 # multiply array by scalar value +array([ 0.,0.0314,...,6.252]) +# apply functions to array. +>>> y = sin(x) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More examples of \num} +\vspace*{-8pt} +\begin{lstlisting} +# Size, shape, rank, type etc. +>>> x = array([1., 2, 3, 4]) +>>> size(x) +4 +>>> x.dtype # or x.dtype.char +'d' +>>> x.shape +(4,) +>>> print rank(x), x.itemsize +1 8 +>>> x.tolist() +[1.0, 2.0, 3.0, 4.0] +# Array indexing +>>> x[0] = 10 +>>> print x[0], x[-1] +10.0 4.0 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Multi-dimensional arrays} +\begin{lstlisting} +>>> a = array([[ 0, 1, 2, 3], +... [10,11,12,13]]) +>>> a.shape # (rows, columns) +(2, 4) +# Accessing and setting values +>>> a[1,3] +13 +>>> a[1,3] = -1 +>>> a[1] # The second row +array([10,11,12,-1]) + +# Flatten/ravel arrays to 1D arrays +>>> a.flat # or ravel(a) +array([0,1,2,3,10,11,12,-1]) +# Note: flat references original memory +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Slicing arrays} +\begin{lstlisting} +>>> a = array([[1,2,3], [4,5,6], [7,8,9]]) +>>> a[0,1:3] +array([2, 3]) +>>> a[1:,1:] +array([[5, 6], + [8, 9]]) +>>> a[:,2] +array([3, 6, 9]) +# Striding... +>>> a[0::2,0::2] +array([[1, 3], + [7, 9]]) +# All these slices are references to the same memory! +\end{lstlisting} +\end{frame} + +% \begin{frame}[fragile] +% \frametitle{Array types and typecodes} +% \begin{tabular}[c]{|c|c|p{2.75in}|} +% \hline +% Character & Bits (bytes) & Type name \\ +% \hline +% D & 128 (16) & \typ{Complex, Complex64}\\ +% F & 64 (8) & \typ{Complex0, Complex8, Complex16} \\ +% d & 64 (8) & \typ{Float, Float64} \\ +% f & 32 (4) & \typ{Float0, Float8, Float16} \\ +% i & 32 (4) & \typ{Int32} \\ +% l & 32 (4) & \typ{Int} \\ +% O & 4 (1) & \typ{PyObject} \\ +% %b 8 (1) UnsignedInt8 +% %1 (one) 8 (1) Int8 +% %s 16 (2) Int16 +% \hline +% \end{tabular} +% \begin{lstlisting} +% # Examples +% >>> f = array([1,2,3], Float32) +% >>> c = array([1,2,3], Complex32) +% >>> print f, c +% [ 1. 2. 3.] [ 1.+0.j 2.+0.j 3.+0.j] +% \end{lstlisting} +% \end{frame} + +\begin{frame}[fragile] + \frametitle{Array creation functions} + \begin{itemize} + \item \typ{array(object, dtype=None, copy=1,order=None, subok=0,ndmin=0)} + \item \typ{arange(start, stop=None, step=1, dtype=None)} + \item \typ{linspace(start, stop, num=50, endpoint=True, retstep=False)} + \item \typ{ones(shape, dtype=None, order='C')} + \item \typ{zeros((d1,...,dn),dtype=float,order='C')} + \item \typ{identity(n)} + \item \typ{empty((d1,...,dn),dtype=float,order='C')} + \item \typ{ones\_like(x)}, \typ{zeros\_like(x)}, \typ{empty\_like(x)} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Array math} + \begin{itemize} + \item Basic \alert{elementwise} math (given two arrays \typ{a, b}): + \begin{itemize} + \item \typ{a + b $\rightarrow$ add(a, b)} + \item \typ{a - b, $\rightarrow$ subtract(a, b)} + \item \typ{a * b, $\rightarrow$ multiply(a, b)} + \item \typ{a / b, $\rightarrow$ divide(a, b)} + \item \typ{a \% b, $\rightarrow$ remainder(a, b)} + \item \typ{a ** b, $\rightarrow$ power(a, b)} + \end{itemize} + \item Inplace operators: \typ{a += b}, or \typ{add(a, b, + a)} etc. + \item Logical operations: \typ{equal (==)}, \typ{not\_equal (!=)}, + \typ{less (<)}, \typ{greater (>)} etc. + \item Trig and other functions: \typ{sin(x), arcsin(x), sinh(x), + exp(x), sqrt(x)} etc. + \item \typ{sum(x, axis=0), product(x, axis=0)}: sum and product of array elements + \item \typ{dot(a, b)} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Advanced} + \begin{itemize} + \item Only scratched the surface of \num + \item Ufunc methods: \typ{reduce, accumulate, outer, reduceat} + \item Typecasting + \item More functions: \typ{take, choose, where, compress, + concatenate} + \item Array broadcasting and \typ{None} + \end{itemize} +\end{frame} + +\subsection{Plotting: Matplotlib} + +\begin{frame} + \frametitle{About \texttt{matplotlib}} + \begin{itemize} + \item Easy to use, scriptable, ``Matlab-like'' 2D plotting + \item Publication quality figures and interactive capabilities + \item Plots, histograms, power spectra, bar charts, errorcharts, + scatterplots, etc. + \item Also does polar plots, maps, contours + \item Support for simple \TeX\ markup + \item Multiple output backends (images, EPS, SVG, wx, Agg, Tk, GTK) + \item Cross-platform: Linux, Win32, Mac OS X + \item Good idea to use via IPython: \typ{ipython -pylab} + \item From scripts use: \typ{import pylab} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{More information} + \begin{itemize} + \item More information here: \url{http://matplotlib.sf.net} + \item \url{http://matplotlib.sf.net/tutorial.html} + \item \url{http://matplotlib.sf.net/screenshots.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting with \texttt{matplotlib}} +\begin{lstlisting} +>>> x = arange(0, 2*pi, 0.05) +>>> plot(x, sin(x)) # Same as plot(x, sin(x), 'b-') +>>> plot(x, sin(x), 'ro') +>>> axis([0,2*pi, -1,1]) +>>> xlabel(r'$\chi$', color='g') +>>> ylabel(r'sin($\chi$)', color='r') +>>> title('A simple figure', fontsize=20) +>>> savefig('/tmp/test.eps') +# Multiple plots in one figure +>>> t = arange(0.0, 5.2, 0.2) +# red dashes, blue squares and green triangles +>>> plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting \ldots} +\begin{lstlisting} +# Set properties of objects: +>>> plot(x, sin(x), linewidth=2.0, color='r') +>>> l, = plot(x, sin(x)) +>>> setp(l, linewidth=2.0, color='r') +>>> l.set_linewidth(2.0); l.set_color('r') +>>> draw() # Redraws current figure. +>>> setp(l) # Prints available properties +>>> close() # Closes the figure. +# Multiple figures: +>>> figure(1); plot(x, sin(x)) +>>> figure(2); plot(x, tanh(x)) +>>> figure(1); title('Easy as 1,2,3') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting \ldots} +\begin{lstlisting} +>>> figure(1) +>>> subplot(211) # Same as subplot(2, 1, 1) +>>> plot(x, cos(5*x)*exp(-x)) +>>> subplot(2, 1, 2) +>>> plot(x, cos(5*x), 'r--', label='cosine') +>>> plot(x, sin(5*x), 'g--', label='sine') +>>> legend() # Or legend(['cosine', 'sine']) +>>> text(1,0, '(1,0)') +>>> axes = gca() # Current axis +>>> fig = gcf() # Current figure +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{X-Y plot} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/xyplot} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +t1 = arange(0.0, 5.0, 0.1) +t2 = arange(0.0, 5.0, 0.02) +t3 = arange(0.0, 2.0, 0.01) +subplot(211) +plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', + t2, cos(2*pi*t2)*exp(-t2), 'k') +grid(True) +title('A tale of 2 subplots') +ylabel('Damped') +subplot(212) +plot(t3, cos(2*pi*t3), 'r--') +grid(True) +xlabel('time (s)') +ylabel('Undamped') +\end{lstlisting} + \end{block} + \end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Errorbar} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/errorbar} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +t = arange(0.1, 4, 0.1) +s = exp(-t) +e = 0.1*abs(randn(len(s))) +f = 0.1*abs(randn(len(s))) +g = 2*e +h = 2*f +errorbar(t, s, [e,g], f, fmt='o') +xlabel('Distance (m)') +ylabel('Height (m)') +title('Mean and standard error '\ + 'as a function of distance') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Semi-log and log-log plots} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/log} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +dt = 0.01 +t = arange(dt, 20.0, dt) +subplot(311) +semilogy(t, exp(-t/5.0)) +ylabel('semilogy') +grid(True) +subplot(312) +semilogx(t, sin(2*pi*t)) +ylabel('semilogx') +grid(True) +# minor grid on too +gca().xaxis.grid(True, which='minor') +subplot(313) +loglog(t, 20*exp(-t/10.0), basex=4) +grid(True) +ylabel('loglog base 4 on x') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Histogram} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/histogram} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +mu, sigma = 100, 15 +x = mu + sigma*randn(10000) +# the histogram of the data +n, bins, patches = hist(x, 100, normed=1) +# add a 'best fit' line +y = normpdf( bins, mu, sigma) +l = plot(bins, y, 'r--', linewidth=2) +xlim(40, 160) +xlabel('Smarts') +ylabel('P') +title(r'$\rm{IQ:}\/ \mu=100,\/ \sigma=15$') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Bar charts} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/barchart} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +N = 5 +menMeans = (20, 35, 30, 35, 27) +menStd = ( 2, 3, 4, 1, 2) +# the x locations for the groups +ind = arange(N) +# the width of the bars +width = 0.35 +p1 = bar(ind, menMeans, width, + color='r', yerr=menStd) +womenMeans = (25, 32, 34, 20, 25) +womenStd = ( 3, 5, 2, 3, 3) +p2 = bar(ind+width, womenMeans, width, + color='y', yerr=womenStd) +ylabel('Scores') +title('Scores by group and gender') +xticks(ind+width, + ('G1', 'G2', 'G3', 'G4', 'G5')) +xlim(-width,len(ind)) +yticks(arange(0,41,10)) +legend((p1[0], p2[0]), + ('Men', 'Women'), shadow=True) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Pie charts} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.4in} + \includegraphics[height=2.0in, interpolate=true]{data/piechart} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +# make a square figure and axes +figure(1, figsize=(8,8)) +ax = axes([0.1, 0.1, 0.8, 0.8]) +labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' +fracs = [15,30,45, 10] +explode=(0, 0.05, 0, 0) +pie(fracs, explode=explode, labels=labels, + autopct='%1.1f%%', shadow=True) +title('Raining Hogs and Dogs', + bbox={'facecolor':'0.8', 'pad':5}) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Scatter plots} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.4in} + \includegraphics[height=2in, interpolate=true]{data/scatter} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +N = 30 +x = 0.9*rand(N) +y = 0.9*rand(N) +# 0 to 10 point radiuses +area = pi*(10 * rand(N))**2 +volume = 400 + rand(N)*450 +scatter(x,y,s=area, marker='o', c=volume, + alpha=0.75) +xlabel(r'$\Delta_i$', size='x-large') +ylabel(r'$\Delta_{i+1}$', size='x-large') +title(r'Volume and percent change') +grid(True) +colorbar() +savefig('scatter') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Polar} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/polar} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +figure(figsize=(8,8)) +ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, + axisbg='#d5de9c') +r = arange(0,1,0.001) +theta = 2*2*pi*r +polar(theta, r, color='#ee8d18', lw=3) +# the radius of the grid labels +setp(ax.thetagridlabels, y=1.075) +title(r"$\theta=4\pi r", fontsize=20) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Contours} + \begin{columns} + \column{0.45\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/contour} + \column{0.525\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +x = arange(-3.0, 3.0, 0.025) +y = arange(-2.0, 2.0, 0.025) +X, Y = meshgrid(x, y) +Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) +# difference of Gaussians +Z = 10.0 * (Z2 - Z1) +im = imshow(Z, interpolation='bilinear', + origin='lower', + cmap=cm.gray, extent=(-3,3,-2,2)) +levels = arange(-1.2, 1.6, 0.2) +# label every second level +clabel(CS, levels[1::2], inline=1, + fmt='%1.1f', fontsize=14) +CS = contour(Z, levels, + origin='lower', + linewidths=2, + extent=(-3,3,-2,2)) +# make a colorbar for the contour lines +CB = colorbar(CS, shrink=0.8, extend='both') +title('Lines with colorbar') +hot(); flag() +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Velocity vectors} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/quiver} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +X,Y = meshgrid(arange(0,2*pi,.2), + arange(0,2*pi,.2) ) +U = cos(X) +V = sin(Y) +Q = quiver(X[::3, ::3], Y[::3, ::3], + U[::3, ::3], V[::3, ::3], + color='r', units='x', + linewidths=(2,), + edgecolors=('k'), + headaxislength=5 ) +qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', + fontproperties= + {'weight': 'bold'}) +axis([-1, 7, -1, 7]) +title('triangular head; scale '\ + 'with x view; black edges') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Maps} + \includegraphics[height=2.5in, interpolate=true]{data/plotmap} + \begin{center} + \tiny + For details see \url{http://matplotlib.sourceforge.net/screenshots/plotmap.py} + \end{center} +\end{frame} + + +\subsection{SciPy} + +\begin{frame} + \frametitle{Using \texttt{SciPy}} + \begin{itemize} + \item SciPy is Open Source software for mathematics, science, and + engineering + \item \typ{import scipy} + \item Built on NumPy + \item Provides modules for statistics, optimization, integration, + linear algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + \item Used widely by scientists world over + \item Details are beyond the scope of this tutorial + \end{itemize} +\end{frame} + +\section{Standard library} + +\subsection{Quick Tour} + +\begin{frame} + \frametitle{Standard library} + \begin{itemize} + \item Very powerful + \item ``Batteries included'' + \item Example standard modules taken from the tutorial + \begin{itemize} + \item Operating system interface: \typ{os} + \item System, Command line arguments: \typ{sys} + \item Regular expressions: \typ{re} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib2}, \typ{smtplib} + \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, + \typ{zipfile}, and \typ{tarfile} + \item Unit testing: \typ{doctest} and \typ{unittest} + \item And a whole lot more! + \end{itemize} + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import os +>>> os.system('date') +Fri Jun 10 22:13:09 IST 2005 +0 +>>> os.getcwd() +'/home/prabhu' +>>> os.chdir('/tmp') +>>> import os +>>> dir(os) +<returns a list of all module functions> +>>> help(os) +<extensive manual page from module's docstrings> +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import sys +>>> # Print the list of command line args to Python +... print sys.argv +[''] +>>> import re # Regular expressions +>>> re.findall(r'\bf[a-z]*', +... 'which foot or hand fell fastest') +['foot', 'fell', 'fastest'] +>>> re.sub(r'(\b[a-z]+) \1', r'\1', +... 'cat in the the hat') +'cat in the hat' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import math +>>> math.cos(math.pi / 4.0) +0.70710678118654757 +>>> math.log(1024, 2) +10.0 +>>> import random +>>> random.choice(['apple', 'pear', 'banana']) +'pear' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import urllib2 +>>> f = urllib2.urlopen('http://www.python.org/') +>>> print f.read(100) +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<?xml-stylesheet href="./css/ht2html +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import zlib +>>> s = 'witch which has which witches wrist watch' +>>> len(s) +41 +>>> t = zlib.compress(s) +>>> len(t) +37 +>>> zlib.decompress(t) +'witch which has which witches wrist watch' +>>> zlib.crc32(t) +-1438085031 +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Introduced Python + \item Basic syntax + \item Basic types and data structures + \item Control flow + \item Functions + \item Modules + \item Exceptions + \item Classes + \item Standard library + \end{itemize} +\end{frame} + +\end{document} + +\subsection{Basic data structures} +\begin{frame}{Lists} + \begin{itemize} + \item \texttt{species = [ 'humans', 'orcs', 'elves', 'dwarves' ]} + \item \texttt{ ids = [ 107, 109, 124, 141, 142, 144 ]} + \item \texttt{ oneliners = [ 'I will be back', 'Do or do not! No try!!', 42 ] } + \end{itemize} + + \begin{block}{List operations} + ids + [ 100, 102 ]\\ + species.append( 'unicorns')\\ + print oneliners[ 1 ]\\ + look up \alert{docs.python.org/tutorial/datastructures.html} + \end{block} +\end{frame} +\end{document} +\section{Python Tutorial} +\subsection{Preliminaries} +\begin{frame} + \frametitle{Using the interpreter} + \begin{itemize} + \item Starting up: \typ{python} or \typ{ipython} + \item Quitting: \typ{Control-D} or \typ{Control-Z} (on Win32) + \item Can use it like a calculator + \item Can execute one-liners via the \typ{-c} option: + \typ{python -c "print 'hello world'"} + \item Other options via \typ{python -h} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{IPython} + \begin{itemize} + \item Recommended interpreter, IPython: + \url{http://ipython.scipy.org} + \item Better than the default Python shell + \item Supports tab completion by default + \item Easier object introspection + \item Shell access! + \item Command system to allow extending its own behavior + \item Supports history (across sessions) and logging + \item Can be embedded in your own Python code + \item Support for macros + \item A flexible framework for your own custom interpreter + \item Other miscellaneous conveniences + \item We'll get back to this later + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic IPython features} + \begin{itemize} + \item Startup: \verb+ipython [options] files+ + \begin{itemize} + \item \verb+ipython [-wthread|-gthread|-qthread]+: + Threading modes to support wxPython, pyGTK and Qt + \item \verb+ipython -pylab+: Support for matplotlib + \end{itemize} + \item TAB completion: + \begin{itemize} + \item Type \verb+object_name.<TAB>+ to see list of options + \item Also completes on file and directory names + \end{itemize} + \item \verb+object?+ shows docstring/help for any Python object + \item \verb+object??+ presents more docs (and source if possible) + \item Debugging with \verb+%pdb+ magic: pops up pdb on errors + \item Access history (saved over earlier sessions also) + \begin{itemize} + \item Use \texttt{<UpArrow>}: move up history + \item Use \texttt{<Ctrl-r> string}: search history backwards + \item Use \texttt{Esc >}: get back to end of history + \end{itemize} + \item \verb+%run [options] file[.py]+ lets you run Python code + \end{itemize} +\end{frame} +% LocalWords: BDFL Guido Rossum PSF Nokia OO Zope CMS RedHat SciPy MayaVi spam +% LocalWords: IPython ipython stdin TypeError dict int elif PYTHONPATH IOError +% LocalWords: namespace Namespaces SyntaxError ZeroDivisionError NameError str +% LocalWords: ValueError subclassed def + + + \item Types are of two kinds: \alert{mutable} and \alert{immutable} + \item Immutable types: numbers, strings, \typ{None} and tuples + \item Immutables cannot be changed ``in-place'' + \item Mutable types: lists, dictionaries, instances, etc. + \item Mutable objects can be ``changed'' + \end{itemize} + + +\begin{frame} + \frametitle{Important!} + \begin{itemize} + \item Assignment to an object is by reference + \item Essentially, \alert{names are bound to objects} + \end{itemize} +\end{frame} + + +\end{document} +\begin{frame}[fragile] + \frametitle{Dictionaries} + \begin{itemize} + \item Associative arrays/mappings + \item Indexed by ``keys'' (keys must be immutable) + \item \typ{dict[key] = value} + \item \typ{keys()} returns all keys of the dict + \item \typ{values()} returns the values of the dict + \item \verb+has_key(key)+ returns if \typ{key} is in the dict + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries: example} + \begin{lstlisting} +>>> tel = {'jack': 4098, 'sape': 4139} +>>> tel['guido'] = 4127 +>>> tel +{'sape': 4139, 'guido': 4127, 'jack': 4098} +>>> tel['jack'] +4098 +>>> del tel['sape'] +>>> tel['irv'] = 4127 +>>> tel +{'guido': 4127, 'irv': 4127, 'jack': 4098} +>>> tel.keys() +['guido', 'irv', 'jack'] +>>> tel.has_key('guido') +True + \end{lstlisting} +\end{frame} + +\subsection{Control flow, functions} + + + +\begin{frame}[fragile] + \frametitle{\typ{If} example} + \begin{lstlisting} +>>> a = ['cat', 'window', 'defenestrate'] +>>> if 'cat' in a: +... print "meaw" +... +meaw +>>> pets = {'cat': 1, 'dog':2, 'croc': 10} +>>> if 'croc' in pets: +... print pets['croc'] +... +10 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for} example} + \begin{lstlisting} +>>> a = ['cat', 'window', 'defenestrate'] +>>> for x in a: +... print x, len(x) +... +cat 3 +window 6 +defenestrate 12 +>>> knights = {'gallahad': 'the pure', +... 'robin': 'the brave'} +>>> for k, v in knights.iteritems(): +... print k, v +... +gallahad the pure +robin the brave +\end{lstlisting} +\end{frame} diff --git a/day1/Session-4.tex b/day1/Session-4.tex new file mode 100755 index 0000000..0e0fd96 --- /dev/null +++ b/day1/Session-4.tex @@ -0,0 +1,2745 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Tutorial slides on Python. +% +% Author: Prabhu Ramachandran <prabhu at aero.iitb.ac.in> +% Copyright (c) 2005-2008, Prabhu Ramachandran +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} +%\documentclass[draft]{beamer} +%\documentclass[compress,handout]{beamer} +%\usepackage{pgfpages} +%\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] + +% Modified from: generic-ornate-15min-45min.de.tex +\mode<presentation> +{ + \usetheme{Warsaw} + \useoutertheme{split} + \setbeamercovered{transparent} +} + +\usepackage[english]{babel} +\usepackage[latin1]{inputenc} +%\usepackage{times} +\usepackage[T1]{fontenc} + +% Taken from Fernando's slides. +\usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} +\usepackage[scaled=.95]{helvet} + +\definecolor{darkgreen}{rgb}{0,0.5,0} + +\usepackage{listings} +\lstset{language=Python, + basicstyle=\ttfamily, + commentstyle=\color{red}\itshape, + stringstyle=\color{darkgreen}, + showstringspaces=false, + keywordstyle=\color{blue}\bfseries} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Macros +\setbeamercolor{emphbar}{bg=blue!20, fg=black} +\newcommand{\emphbar}[1] +{\begin{beamercolorbox}[rounded=true]{emphbar} + {#1} + \end{beamercolorbox} +} +\newcounter{time} +\setcounter{time}{0} +\newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} + +\newcommand{\typ}[1]{\texttt{#1}} + +\newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } + +%%% This is from Fernando's setup. +% \usepackage{color} +% \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} +% % Use and configure listings package for nicely formatted code +% \usepackage{listings} +% \lstset{ +% language=Python, +% basicstyle=\small\ttfamily, +% commentstyle=\ttfamily\color{blue}, +% stringstyle=\ttfamily\color{orange}, +% showstringspaces=false, +% breaklines=true, +% postbreak = \space\dots +% } + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Basic Python]{Python:\\A great programming toolkit} + +\author[Asokan \& Prabhu] {Asokan Pichai\\Prabhu Ramachandran} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {25, July 2009} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} +%\logo{\pgfuseimage{iitmlogo}} + + +%% Delete this, if you do not want the table of contents to pop up at +%% the beginning of each subsection: +\AtBeginSubsection[] +{ + \begin{frame}<beamer> + \frametitle{Outline} + \tableofcontents[currentsection,currentsubsection] + \end{frame} +} + + +% If you wish to uncover everything in a step-wise fashion, uncomment +% the following command: +%\beamerdefaultoverlayspecification{<+->} + +%\includeonlyframes{current,current1,current2,current3,current4,current5,current6} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% DOCUMENT STARTS +\begin{document} + +\begin{frame} + \titlepage +\end{frame} +\begin{frame} + {Acknowledgements} + \begin{center} + This program is conducted by\\ + IIT, Bombay\\ + through CDEEP\\as part of the open source initiatives\\ + under the aegis of\\ + \alert{National Mission on Education through ICT,} \\ + Ministry of HRD. + \end{center} +\end{frame} + +\begin{frame} + \frametitle{Outline} + \tableofcontents + % You might wish to add the option [pausesections] +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TODO +% +% * Add slide on Python packages (modules) +% * Add slides on reference counting. + +\section{Agenda} +\begin{frame}{About the Workshop} + \begin{description} + \item[Session 1] Sat 14:00--15:55 + \item[Session 2] Sat 16:05--18:00 + \item[Session 3] Sun 14:00--15:55 + \item[Session 4] Sun 16:05--18:00 + \end{description} + + \begin{block}{Goal of the workshop} + At the end of this program, successful participants will be able to use python as their scripting and problem solving language. Aimed at Engg. students--focus on basic numerics and plotting-- but should serve a similar purpose for others. + \end{block} +\end{frame} + +\begin{frame}{Checklist} + Let us verify that all of us are having the same (similar) tools and environment + \begin{description} + \item[python] Type python at the command line. Do you see version 2.5 or later? + \item[IPython] Is IPython available? + \item[Editor] Which editor? scite, vim, emacs, \ldots + \end{description} +\end{frame} + +\section{Overview} +\begin{frame}{Session 1} + \begin{itemize} + \item Introduction and motivation + \item Using the interpreter(s) + \item Basic data types: int, float, string + \item Basic data structures: list + \item Basic console IO: \texttt{raw\_input(), print} + \item Basic control flow: \texttt{if, while} + \item Problem set 1 + \item Functions $\rightarrow$ Problem set 2 + \item lists, \texttt{for} $\rightarrow$ Problem set 3 + \item IO, Modules $\rightarrow$ Problem sets 4,5, \ldots + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Introduction} + \begin{itemize} + \item Creator and BDFL: Guido van Rossum + \item Conceived in December 1989 + \item ``Python'' as in Monty Python's Flying Circus + \item Current stable version of Python is 2.6.x + \item PSF license (like BSD: no strings attached) + \item Highly cross platform + \item Runs on the Nokia series 60! + \item \alert{Philosophy:} Simple and complete by design + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Resources} + \begin{itemize} + \item Part of many GNU/Linux distributions + \item Web: \url{http://www.python.org} + \item Doc: \url{http://www.python.org/doc} + \item Free Tutorials: + \begin{itemize} + \item Official Python tutorial: \url{http://docs.python.org/tut/tut.html} + \item Byte of Python: \url{http://www.byteofpython.info/} + \item Dive into Python: \url{http://diveintopython.org/} + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Why Python?} + \begin{itemize} + \item Designed to be readable and easy to use + \item High level, interpreted, modular, OO + \item Much faster development cycle + \item Powerful interactive environment + \item Rapid application development + \item Rich standard library and modules + \item Interfaces well with C++, C and FORTRAN + \item \alert{More than a math package $\Rightarrow$ some extra work compared to math packages} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Use cases} + \begin{itemize} + \item NASA: Space Shuttle Mission Design + \item AstraZeneca: Collaborative Drug Discovery + \item ForecastWatch.com: Helps Meteorologists + \item Industrial Light \& Magic: Runs on Python + \item Zope: Commercial grade Toolkit + \item Plone: Professional high feature CMS + \item RedHat: install scripts, sys-admin tools + \item Django: A great web application framework + \item Google: A strong python shop + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{To sum up, python is\ldots} + \begin{itemize} + \item dynamically typed, interpreted $\rightarrow$ rapid testing/prototyping + \item powerful, very high level + \item has full introspection + \item Did we mention powerful? + \end{itemize} + \begin{block}{But \ldots} + may be wanting in performance. specialised resources such as SWIG, \alert{Cython} are available + \end{block} + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 15m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\section{Python} + +\subsection{Getting Started} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> print 'Hello Python' +>>> print 3124 * 126789 +>>> 1786 % 12 +>>> 3124 * 126789 +>>> a = 3124 * 126789 +>>> big = 12345678901234567890 ** 3 +>>> verybig = big * big * big * big +>>> 12345**6, 12345**67, 12345**678 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> s = 'Hello ' +>>> p = 'World' +>>> s + p +>>> s * 12 +>>> s * s +>>> s + p * 12, (s + p)* 12 +>>> s * 12 + p * 12 +>>> 12 * s + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{At the prompt, type the following} + \begin{lstlisting} +>>> 17/2 +>>> 17/2.0 +>>> 17.0/2 +>>> 17.0/8.5 +>>> int(17/2.0) +>>> float(17/2) +>>> str(17/2.0) +>>> round( 7.5 ) + \end{lstlisting} + \begin{block}{Mini exercise} + Round a float to the nearest integer, using \texttt{int()}? + \end{block} +\end{frame} + +\begin{frame}{Midi exercises} + \begin{center} + \begin{itemize} + \item What does this do? + \item \texttt{round(amount * 10) /10.0 } + \end{itemize} + \end{center} +\end{frame} + +\begin{frame}{More exercises?} + \begin{center} + \begin{block}{Round sums} + How to round a number to the nearest 5 paise?\\ + \begin{description} + \item[Remember] 17.23 $\rightarrow$ 17.25,\\ while 17.22 $\rightarrow$ 17.20\\ + \end{description} + How to round a number to the nearest 20 paise? + \end{block} + \end{center} +\end{frame} + +\begin{frame}[fragile] {A question of good style} + \begin{lstlisting} + amount = 12.68 + denom = 0.05 + nCoins = round(amount/denom) + rAmount = nCoins * denom + \end{lstlisting} + \pause + \begin{block}{Style Rule \#1} + Naming is 80\% of programming + \end{block} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item Case sensitive + \item Dynamically typed $\Rightarrow$ need not specify a type + \begin{lstlisting} +a = 1 +a = 1.1 +a = "Now I am a string!" + \end{lstlisting} + \item Comments: + \begin{lstlisting} +a = 1 # In-line comments +# Comment in a line to itself. +a = "# This is not a comment!" + \end{lstlisting} + \end{itemize} + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 30m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Data types} +\begin{frame} + \frametitle{Basic types} + \begin{itemize} + \item numbers: float, int, long, complex + \item strings + \item boolean + \end{itemize} + \begin{block}{Also to be discussed later} + tuples, lists, dictionaries, functions, objects\ldots + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Numbers} + \vspace*{-0.25in} + \begin{lstlisting} +>>> a = 1 # Int. +>>> l = 1000000L # Long +>>> e = 1.01325e5 # float +>>> f = 3.14159 # float +>>> c = 1+1j # Complex! +>>> print f*c/a +(3.14159+3.14159j) +>>> print c.real, c.imag +1.0 1.0 +>>> abs(c) +1.4142135623730951 +>>> abs( 8 - 9.5 ) +1.5 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Boolean} + \begin{lstlisting} +>>> t = True +>>> f = not t +False +>>> f or t +True +>>> f and t +False + \end{lstlisting} + \begin{block}{Try:} + NOT True\\ + not TRUE + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Relational and logical operators} + \begin{lstlisting} +>>> a, b, c = -1, 0, 1 +>>> a == b +False +>>> a <= b +True +>>> a + b != c +True +>>> a < b < c +True +>>> c >= a + b +True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Strings} + \begin{lstlisting} +s = 'this is a string' +s = 'This one has "quotes" inside!' +s = "I have 'single-quotes' inside!" +l = "A string spanning many lines\ +one more line\ +yet another" +t = """A triple quoted string does +not need to be escaped at the end and +"can have nested quotes" etc.""" + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More Strings} + \vspace*{-0.2in} + \begin{lstlisting} +>>> w = "hello" +>>> print w[0] + w[2] + w[-1] +hlo +>>> len(w) # guess what +5 +>>> s = u'Unicode strings!' +>>> # Raw strings (note the leading 'r') +... r_s = r'A string $\alpha \nu$' + \end{lstlisting} +\pause + \begin{lstlisting} +>>> w[0] = 'H' # Can't do that! +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: object does not support item assignment + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Let us switch to IPython} + Why? + \begin{block} + {Better help (and a lot more)} + Tab completion\\ + ?\\ + .?\\ + object.function? + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More on strings} + \begin{lstlisting} +In [1]: a = 'hello world' +In [2]: a.startswith('hell') +Out[2]: True +In [3]: a.endswith('ld') +Out[3]: True +In [4]: a.upper() +Out[4]: 'HELLO WORLD' +In [5]: a.upper().lower() +Out[5]: 'hello world' + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Still with strings} + \begin{lstlisting} +In [6]: a.split() +Out[6]: ['hello', 'world'] +In [7]: ''.join(['a', 'b', 'c']) +Out[7]: 'abc' +In [8] 'd' in ''.join( 'a', 'b', 'c') +Out[8]: False + \end{lstlisting} + \begin{block}{Try:} + \texttt{a.split( 'o' )}\\ + \texttt{'x'.join( a.split( 'o' ) )} + \end{block} +\end{frame} + +\begin{frame}[fragile]{Surprise! strings!!} + \begin{lstlisting} +In [11]: x, y = 1, 1.2 +In [12]: 'x is %s, y is %s' %(x, y) +Out[12]: 'x is 1, y is 1.234' + \end{lstlisting} + \begin{block}{Try:} + \texttt{'x is \%d, y is \%f' \%(x, y) }\\ + \texttt{'x is \%3d, y is \%4.2f' \%(x, y) } + \end{block} + \small +\url{docs.python.org/lib/typesseq-strings.html}\\ +\end{frame} + +\begin{frame} + {Interlude} + \begin{block} + {A classic problem} + How to interchange values of two variables? Please note that the type of either variable is unknown and it is not necessary that both be of the same type even! + \end{block} + \inctime{30} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 25 m+ Interlude break 5 mins, running 60m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Control flow} +\begin{frame} + \frametitle{Control flow constructs} + \begin{itemize} + \item \kwrd{if/elif/else}: branching + \item \kwrd{while}: looping + \item \kwrd{for}: iterating + \item \kwrd{break, continue}: modify loop + \item \kwrd{pass}: syntactic filler + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic conditional flow} + \begin{lstlisting} +In [21]: a = 7 +In [22]: b = 8 +In [23]: if a > b: + ....: print 'Hello' + ....: else: + ....: print 'World' + ....: + ....: +World + \end{lstlisting} + Let us switch to creating a file +\end{frame} + +\begin{frame} + {Creating python files} + \begin{itemize} + \item aka scripts + \item use your editor + \item Note that white space is the way to specify blocks! + \item extension \typ{.py} + \item run with \texttt{python hello.py} at the command line + \item in IPython\ldots + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{If...elif...else} example} +\begin{lstlisting} +x = int(raw_input("Enter an integer:")) +if x < 0: + print 'Be positive!' +elif x == 0: + print 'Zero' +elif x == 1: + print 'Single' +else: + print 'More' +\end{lstlisting} +\end{frame} + +\begin{frame}{Simple IO} + \begin{block} + {Console Input} + \texttt{raw\_input(}) waits for user input.\\Prompt string is optional.\\ + All keystrokes are Strings!\\\texttt{int()} converts string to int. + \end{block} + \begin{block} + {Console output} + \texttt{print} is straight forward. Major point to remember is the distinction between \texttt{print x} and \texttt{print x,} + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic looping} + \begin{lstlisting} +# Fibonacci series: +# the sum of two elements +# defines the next +a, b = 0, 1 +while b < 10: + print b, + a, b = b, a + b + +\end{lstlisting} +\typ{1 1 2 3 5 8}\\ +\alert{Recall it is easy to write infinite loops with \kwrd{while}} + \inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 80m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + \frametitle{Problem set 1} + \begin{itemize} + \item All the problems can be\\ + solved using \kwrd{if} and \kwrd{while} + \end{itemize} +\end{frame} + +\begin{frame}{Problem 1.1} + Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ +These are called $Armstrong$ numbers. +\end{frame} + +\begin{frame}{Problem 1.2 - Collatz sequence} +\begin{enumerate} + \item Start with an arbitrary (positive) integer. + \item If the number is even, divide by 2; if the number is odd multiply by 3 and add 1. + \item Repeat the procedure with the new number. + \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. +\end{enumerate} + Write a program that accepts the starting value and prints out the Collatz sequence. + +\end{frame} + +\begin{frame}{Problem 1.3 - Kaprekar's constant} + \begin{enumerate} + \item Take a four digit number--with at least two digits different. + \item Arrange the digits in ascending and descending order, giving A and D respectively. + \item Leave leading zeros in A! + \item Subtract A from D. + \item With the result, repeat from step 2. + \end{enumerate} + Write a program to accept a 4-digit number and display the progression to Kaprekar's constant. +\end{frame} + +\begin{frame}[fragile]{Problem 1.4} + Write a program that prints the following pyramid on the screen. + \begin{lstlisting} +1 +2 2 +3 3 3 +4 4 4 4 + \end{lstlisting} +The number of lines must be obtained from the user as input.\\ +\pause +When can your code fail? +\only<2->{\inctime{25}} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 25 m, running 105m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Functions} +\begin{frame}[fragile] +\frametitle{Functions: examples} + \begin{lstlisting} +def signum( r ): + """returns 0 if r is zero + -1 if r is negative + +1 if r is positive""" + if r < 0: + return -1 + elif r > 0: + return 1 + else: + return 0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: examples} + \begin{lstlisting} +def pad( n, size ): + """pads integer n with spaces + into a string of length size + """ + SPACE = ' ' + s = str( n ) + padSize = size - len( s ) + return padSize * SPACE + s + \end{lstlisting} +\pause +What about \%3d? +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} + \begin{lstlisting} +def what( n ): + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} +\begin{lstlisting} +def what( n ): + i = 1 + while i * i < n: + i += 1 + return i * i == n, i + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {What does this function do?} + \begin{lstlisting} +def what( n, x ): + z = 1.0 + if n < 0: + x = 1.0 / x + n = -n + while n > 0: + if n % 2 == 1: + z *= x + n /= 2 + x *= x + return z + \end{lstlisting} +\end{frame} + +\begin{frame} + {Before writing a function} + \begin{itemize} + \item Builtin functions for various and sundry + \item \typ{abs, any, all, len, max, min} + \item \typ{pow, range, sum, type} + \item Refer here: + \url{http://docs.python.org/library/functions.html} + \end{itemize} + \inctime{15} +\end{frame} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 120m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame}{Problem set 2} + The focus is on writing functions and calling them. +\end{frame} + +\begin{frame}{Problem 2.1} + Write a function to return the gcd of two numbers. +\end{frame} + +\begin{frame}{Problem 2.2} +A pythagorean triad $(a,b,c)$ has the property $a^2 + b^2 = c^2$.\\By primitive we mean triads that do not `depend' on others. For example, (4,3,5) is a variant of (3,4,5) and hence is not primitive. And (10,24,26) is easily derived from (5,12,13) and should not be displayed by our program. \\ +Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100 +\end{frame} + +\begin{frame}{Problem 2.3} + Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\\For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square). +\end{frame} + +\begin{frame}{Problem 2.4} + The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. For example, the aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.\\ + Write a function that returns the aliquot number of a given number. +\end{frame} + +\begin{frame}{Problem 2.5} + A pair of numbers (a, b) is said to be \alert{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ + Example: \texttt{220, 284}\\ + Write a program that prints all five digit amicable pairs. + \inctime{30} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 30 m, running 150m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Lists} + +\begin{frame}[fragile] + \frametitle{List creation and indexing} +\begin{lstlisting} +>>> a = [] # An empty list. +>>> a = [1, 2, 3, 4] # More useful. +>>> len(a) +4 +>>> a[0] + a[1] + a[2] + a[-1] +10 +\end{lstlisting} + \begin{itemize} + \item Indices start with ? + \item Negative indices indicate ? + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: slices} + \begin{itemize} + \item Slicing is a basic operation + \item \typ{list[initial:final:step]} + \item The step is optional + \end{itemize} +\begin{lstlisting} +>>> a[1:3] # A slice. +[2, 3] +>>> a[1:-1] +[2, 3, 4] +>>> a[1:] == a[1:-1] +False +\end{lstlisting} +Explain last result +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: more slices} +\begin{lstlisting} +>>> a[0:-1:2] # Notice the step! +[1, 3] +>>> a[::2] +[1, 3] +>>> a[-1::-1] +\end{lstlisting} +What do you think the last one will do? + \emphbar{Note: Strings also use same indexing and slicing.} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List: examples} +\begin{lstlisting} +>>> a = [1, 2, 3, 4] +>>> a[:2] +[1, 3] +>>> a[0:-1:2] +[1, 3] +\end{lstlisting} +\pause +\alert{Lists are mutable (unlike strings)} +\begin{lstlisting} +>>> a[1] = 20 +>>> a +[1, 20, 3, 4] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists are mutable and heterogenous} +\begin{lstlisting} +>>> a = ['spam', 'eggs', 100, 1234] +>>> a[2] = a[2] + 23 +>>> a +['spam', 'eggs', 123, 1234] +>>> a[0:2] = [1, 12] # Replace items +>>> a +[1, 12, 123, 1234] +>>> a[0:2] = [] # Remove items +>>> a.append( 12345 ) +>>> a +[123, 1234, 12345] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List methods} +\begin{lstlisting} +>>> a = ['spam', 'eggs', 1, 12] +>>> a.reverse() # in situ +>>> a +[12, 1, 'eggs', 'spam'] +>>> a.append(['x', 1]) +>>> a +[12, 1, 'eggs', 'spam', ['x', 1]] +>>> a.extend([1,2]) # Extend the list. +>>> a.remove( 'spam' ) +>>> a +[12, 1, 'eggs', ['x', 1], 1, 2] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List containership} + \begin{lstlisting} +>>> a = ['cat', 'dog', 'rat', 'croc'] +>>> 'dog' in a +True +>>> 'snake' in a +False +>>> 'snake' not in a +True +>>> 'ell' in 'hello world' +True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Tuples: immutable} +\begin{lstlisting} +>>> t = (0, 1, 2) +>>> print t[0], t[1], t[2], t[-1] +0 1 2 2 +>>> t[0] = 1 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: object does not support item + assignment +\end{lstlisting} +\begin{itemize} + \item Multiple return values are actually a tuple. + \item Exchange is tuple (un)packing +\end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{range()} function} + \begin{lstlisting} +>>> range(7) +[0, 1, 2, 3, 4, 5, 6] +>>> range( 3, 9) +[3, 4, 5, 6, 7, 8] +>>> range( 4, 17, 3) +[4, 7, 10, 13, 16] +>>> range( 5, 1, -1) +[5, 4, 3, 2] +>>> range( 8, 12, -1) +[] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for\ldots range(\ldots)} idiom} + \begin{lstlisting} +In [83]: for i in range(5): + ....: print i, i * i + ....: + ....: +0 0 +1 1 +2 4 +3 9 +4 16 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for}: the list companion} + + \begin{lstlisting} +In [84]: a = ['a', 'b', 'c'] +In [85]: for x in a: + ....: print x, chr( ord(x) + 10 ) + ....: +a k +b l +c m + \end{lstlisting} + Iterating over the list and not the index + reference\\ + what if you want the index? +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for}: the list companion} + \begin{lstlisting} +In [89]: for p, ch in enumerate( a ): + ....: print p, ch + ....: + ....: +0 a +1 b +2 c + \end{lstlisting} +Try: \typ{print enumerate(a)} +\inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 170m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + {Problem set 3} + As you can guess, idea is to use \kwrd{for}! +\end{frame} + +\begin{frame}{Problem 3.1} + Which of the earlier problems is simpler when we use \kwrd{for} instead of \kwrd{while}? +\end{frame} + +\begin{frame}{Problem 3.2} + Given an empty chessboard and one Bishop placed in any square, say (r, c), generate the list of all squares the Bishop could move to. +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.3} + + Given two real numbers \typ{a, b}, and an integer \typ{N}, write a + function named \typ{linspace( a, b, N)} that returns an ordered list + of \typ{N} points starting with \typ{a} and ending in \typ{b} and + equally spaced.\\ + + For example, \typ{linspace(0, 5, 11)}, should return, \\ +\begin{lstlisting} +[ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, + 3.0 , 3.5, 4.0 , 4.5, 5.0 ] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.4a (optional)} + +Use the \typ{linspace} function and generate a list of N tuples of the form\\ +\typ{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions,\begin{itemize} + \item \typ{f(x) = sin(x)} + \item \typ{f(x) = sin(x) + sin(10*x)}. +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 3.4b (optional)} + + Using the tuples generated earlier, determine the intervals where the roots of the functions lie. + + \inctime{15} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 15 m, running 185m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{IO} + +\begin{frame}[fragile] + \frametitle{Simple tokenizing and parsing} + \begin{lstlisting} +s = """The quick brown fox jumped + over the lazy dog""" +for word in s.split(): + print word.capitalize() + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 4.1} + Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \\ + \begin{lstlisting} + [1,3,4,5,6,7,12,15,18,19,20,21] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File handling} +\begin{lstlisting} +>>> f = open('/path/to/file_name') +>>> data = f.read() # Read entire file. +>>> line = f.readline() # Read one line. +>>> f.close() # close the file. +\end{lstlisting} +Writing files +\begin{lstlisting} +>>> f = open('/path/to/file_name', 'w') +>>> f.write('hello world\n') +>>> f.close() +\end{lstlisting} +\begin{itemize} + \item Everything read or written is a string +\end{itemize} +\emphbar{Try \typ{file?} for more help} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File and \kwrd{for}} +\begin{lstlisting} +>>> f = open('/path/to/file_name') +>>> for line in f: +... print line +... +\end{lstlisting} +\end{frame} + +\begin{frame}{Problem 4.2} + The given file has lakhs of records in the form:\\ + \typ{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}\\ + Some entries may be empty. Read the data from this file and print the + name of the student with the maximum total marks. +\end{frame} + +\begin{frame}{Problem 4.3} + For the same data file compute the average marks in different + subjects, the student with the maximum mark in each subject and also + the standard deviation of the marks. Do this efficiently. + + \inctime{20} +\end{frame} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 205m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\subsection{Modules} + +\begin{frame}[fragile] + {Modules} +\begin{lstlisting} +>>> sqrt(2) +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +NameError: name 'sqrt' is not defined +>>> import math +>>> math.sqrt(2) +1.4142135623730951 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + {Modules} + \begin{itemize} + \item The \kwrd{import} keyword ``loads'' a module + \item One can also use: + \begin{lstlisting} +>>> from math import sqrt +>>> from math import * + \end{lstlisting} + \item What is the difference? + \item \alert{Use the later only in interactive mode} + \end{itemize} + \emphbar{Package hierarchies} + \begin{lstlisting} +>>> from os.path import exists + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Modules: Standard library} + \begin{itemize} + \item Very powerful, ``Batteries included'' + \item Some standard modules: + \begin{itemize} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib2}, \typ{smtplib} + \item System, Command line arguments: \typ{sys} + \item Operating system interface: \typ{os} + \item Regular expressions: \typ{re} + \item Compression: \typ{gzip}, \typ{zipfile}, and \typ{tarfile} + \item And a whole lot more! + \end{itemize} + \item Check out the Python Library reference: + \url{http://docs.python.org/library/} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + {Modules of special interest} + \begin{description}[matplotlibfor2d] + + \item[\typ{numpy}] Efficient, powerful numeric arrays + + \item[\typ{matplotlib}] Easy, interactive, 2D plotting + + \item[\typ{scipy}] statistics, optimization, integration, linear + algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + + \item[Mayavi] Easy, interactive, 3D plotting + + \end{description} +\end{frame} + +\begin{frame}[fragile] + {Creating your own modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \typ{.py} extension + \item This file becomes a module! + \item Accessible when in the current directory + \item Use \typ{cd} in IPython to change directory + + \item Naming your module + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- arith.py --- +def gcd(a, b): + if a%b == 0: return b + return gcd(b, a%b) +def lcm(a, b): + return a*b/gcd(a, b) +# ------------------ +>>> import arith +>>> arith.gcd(26, 65) +13 +>>> arith.lcm(26, 65) +130 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Problem 5.1} + + Put all the functions you have written so far as part of the problems + into one module called \typ{iitb.py} and use this module from IPython. + +\inctime{20} +\end{frame} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% TIME: 20 m, running 225m +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\begin{frame} + \frametitle{Did we meet the goal?} + \tableofcontents + % You might wish to add the option [pausesections] + \end{frame} + + \begin{frame} + {Tomorrow} + \begin{itemize} + \item Plotting: 2D, 3D + \item NumPy, SciPy + \item Dictionary, Set + \item Debugging + \item Testing + \item \ldots + \end{itemize} + 11:30--13:00 Discussion of answers to problems OPTIONAL + \end{frame} +\end{document} + + +\begin{frame}[fragile] + \frametitle{More on functions} + \begin{itemize} + \item Support default and keyword arguments + \item Scope of variables in the function is local + \item Mutable items are \alert{passed by reference} + \item First line after definition may be a documentation string + (\alert{recommended!}) + \item Function definition and execution defines a name bound to the + function + \item You \emph{can} assign a variable to a function! + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Functions: default arguments} + \begin{lstlisting} +def ask_ok(prompt, retries=4, complaint='Yes or no!'): + while True: + ok = raw_input(prompt) + if ok in ('y', 'ye', 'yes'): + return True + if ok in ('n', 'no', 'nop', 'nope'): + return False + retries = retries - 1 + if retries < 0: + raise IOError, 'bad user' + print complaint + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: keyword arguments} + \begin{lstlisting} +def parrot(voltage, state='a stiff', + action='voom', type='Norwegian Blue'): + print "-- This parrot wouldn't", action, + print "if you put", voltage, "Volts through it." + print "-- Lovely plumage, the", type + print "-- It's", state, "!" + +parrot(1000) +parrot(action = 'VOOOOOM', voltage = 1000000) +parrot('a thousand', state = 'pushing up the daisies') +parrot('a million', 'bereft of life', 'jump') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Functions: arbitrary argument lists} + \begin{itemize} + \item Arbitrary number of arguments using \verb+*args+ or + \verb+*whatever+ + \item Keyword arguments using \verb+**kw+ + \item Given a tuple/dict how do you call a function? + \begin{itemize} + \item Using argument unpacking + \item For positional arguments: \verb+foo(*[5, 10])+ + \item For keyword args: \verb+foo(**{'a':5, 'b':10})+ + \end{itemize} + \end{itemize} +\begin{lstlisting} +def foo(a=10, b=100): + print a, b +def func(*args, **keyword): + print args, keyword +# Unpacking: +args = [5, 10] +foo(*args) +kw = {'a':5, 'b':10} +foo(**kw) +\end{lstlisting} +\end{frame} + +\subsection{Modules, exceptions, classes} + +\begin{frame} + \frametitle{Modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \typ{.py} extension + \item This file becomes a module! + \item Modules are searched in the following: + \begin{itemize} + \item Current directory + \item Standard: \typ{/usr/lib/python2.3/site-packages/} etc. + \item Directories specified in PYTHONPATH + \item \typ{sys.path}: current path settings (from the \typ{sys} + module) + \end{itemize} + \item The \typ{import} keyword ``loads'' a module + \item One can also use: + \mbox{\typ{from module import name1, name2, name2}}\\ + where \typ{name1} etc. are names in the module, ``module'' + \item \typ{from module import *} \ --- imports everything from module, + \alert{use only in interactive mode} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- foo.py --- +some_var = 1 +def fib(n): # write Fibonacci series up to n + """Print a Fibonacci series up to n.""" + a, b = 0, 1 + while b < n: + print b, + a, b = b, a+b +# EOF + +>>> import foo +>>> foo.fib(10) +1 1 2 3 5 8 +>>> foo.some_var +1 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Namespaces} + \begin{itemize} + \item A mapping from names to objects + \item Modules introduce a namespace + \item So do classes + \item The running script's namespace is \verb+__main__+ + \item A modules namespace is identified by its name + \item The standard functions (like \typ{len}) are in the + \verb+__builtin__+ namespace + \item Namespaces help organize different names and their bindings to + different objects + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Exceptions} + \begin{itemize} + \item Python's way of notifying you of errors + \item Several standard exceptions: \typ{SyntaxError}, \typ{IOError} + etc. + \item Users can also \typ{raise} errors + \item Users can create their own exceptions + \item Exceptions can be ``caught'' via \typ{try/except} blocks + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exception: examples} +\begin{lstlisting} +>>> 10 * (1/0) +Traceback (most recent call last): + File "<stdin>", line 1, in ? +ZeroDivisionError: integer division or modulo by zero +>>> 4 + spam*3 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +NameError: name 'spam' is not defined +>>> '2' + 2 +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: cannot concatenate 'str' and 'int' objects +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exception: examples} +\begin{lstlisting} +>>> while True: +... try: +... x = int(raw_input("Enter a number: ")) +... break +... except ValueError: +... print "Invalid number, try again..." +... +>>> # To raise exceptions +... raise ValueError, "your error message" +Traceback (most recent call last): + File "<stdin>", line 2, in ? +ValueError: your error message +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: the big picture} + \begin{itemize} + \item Lets you create new data types + \item Class is a template for an object belonging to that class + \item Note: in Python a class is also an object + \item Instantiating a class creates an instance (an object) + \item An instance encapsulates the state (data) and behavior + (methods) + \item Allows you to define an inheritance hierarchy + \begin{itemize} + \item ``A Honda car \alert{is a} car.'' + \item ``A car \alert{is an} automobile.'' + \item ``A Python \alert{is a} reptile.'' + \end{itemize} + \item Programmers need to think OO + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: what's the big deal?} + \begin{itemize} + \item Lets you create objects that mimic a real problem being + simulated + \item Makes problem solving more natural and elegant + \item Easier to create code + \item Allows for code-reuse + \item Polymorphism + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Class definition and instantiation} + \begin{itemize} + \item Class definitions when executed create class objects + \item Instantiating the class object creates an instance of the + class + \end{itemize} +\footnotesize +\begin{lstlisting} +class Foo(object): + pass +# class object created. +# Create an instance of Foo. +f = Foo() +# Can assign an attribute to the instance +f.a = 100 +print f.a +100 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes \ldots} + \begin{itemize} + \item All attributes are accessed via the \typ{object.attribute} + syntax + \item Both class and instance attributes are supported + \item \emph{Methods} represent the behavior of an object: crudely + think of them as functions ``belonging'' to the object + \item All methods in Python are ``virtual'' + \item Inheritance through subclassing + \item Multiple inheritance is supported + \item No special public and private attributes: only good + conventions + \begin{itemize} + \item \verb+object.public()+: public + \item \verb+object._private()+ \& \verb+object.__priv()+: + non-public + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: examples} +\begin{lstlisting} +class MyClass(object): + """Example class (this is the class docstring).""" + i = 12345 # A class attribute + def f(self): + """This is the method docstring""" + return 'hello world' + +>>> a = MyClass() # creates an instance +>>> a.f() +'hello world' +>>> # a.f() is equivalent to MyClass.f(a) +... # This also explains why f has a 'self' argument. +... MyClass.f(a) +'hello world' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes (continued)} + \begin{itemize} + \item \typ{self} is \alert{conventionally} the first argument for a + method + \item In previous example, \typ{a.f} is a method object + \item When \typ{a.f} is called, it is passed the instance \typ{a} as + the first argument + \item If a method called \verb+__init__+ exists, it is called when + the object is created + \item If a method called \verb+__del__+ exists, it is called before + the object is garbage collected + \item Instance attributes are set by simply ``setting'' them in + \typ{self} + \item Other special methods (by convention) like \verb+__add__+ let + you define numeric types: + {\footnotesize \url{http://docs.python.org/ref/specialnames.html} + \\ \url{http://docs.python.org/ref/numeric-types.html} + } + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: examples} +\begin{lstlisting} +class Bag(MyClass): # Shows how to derive classes + def __init__(self): # called on object creation. + self.data = [] # an instance attribute + def add(self, x): + self.data.append(x) + def addtwice(self, x): + self.add(x) + self.add(x) +>>> a = Bag() +>>> a.f() # Inherited method +'hello world' +>>> a.add(1); a.addtwice(2) +>>> a.data +[1, 2, 2] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Derived classes} + \begin{itemize} + \item Call the parent's \verb+__init__+ if needed + \item If you don't need a new constructor, no need to define it in subclass + \item Can also use the \verb+super+ built-in function + \end{itemize} +\begin{lstlisting} +class AnotherBag(Bag): + def __init__(self): + # Must call parent's __init__ explicitly + Bag.__init__(self) + # Alternatively use this: + super(AnotherBag, self).__init__() + # Now setup any more data. + self.more_data = [] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes: polymorphism} +\begin{lstlisting} +class Drawable(object): + def draw(self): + # Just a specification. + pass +\end{lstlisting} +\mode<presentation>{\pause} +\begin{lstlisting} +class Square(Drawable): + def draw(self): + # draw a square. +class Circle(Drawable): + def draw(self): + # draw a circle. +\end{lstlisting} +\mode<presentation>{\pause} +\begin{lstlisting} +class Artist(Drawable): + def draw(self): + for obj in self.drawables: + obj.draw() +\end{lstlisting} +\end{frame} + +\subsection{Miscellaneous} + +\begin{frame}[fragile] + \frametitle{Stand-alone scripts} +Consider a file \typ{f.py}: +\begin{lstlisting} +#!/usr/bin/env python +"""Module level documentation.""" +# First line tells the shell that it should use Python +# to interpret the code in the file. +def f(): + print "f" + +# Check if we are running standalone or as module. +# When imported, __name__ will not be '__main__' +if __name__ == '__main__': + # This is not executed when f.py is imported. + f() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List comprehensions} +\begin{lstlisting} +>>> veg = ['tomato', 'cabbage', 'carrot', 'potato'] +>>> [x.upper() for x in veg] +['TOMATO', 'CABBAGE', 'CARROT', 'POTATO'] +>>> vec = range(0, 8) +>>> even = [x for x in vec if x%2 == 0] +>>> even +[0, 2, 4, 6] +>>> [x*x for x in even] +[0, 4, 16, 36] +>>> odd = [x for x in vec if x%2 == 1] +>>> odd +[1, 3, 5, 7] +>>> [x*y for x in even for y in odd] +[0, 0, 0, 0, 2, 6, 10, 14, 4, 12, 20, 28, 6, 18,30,42] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features} + \begin{itemize} + \item Input and output caching: + \begin{itemize} + \item \verb+In+: a list of all entered input + \item \verb+Out+: a dict of all output + \item \verb+_+, \verb+__+, \verb+__+ are the last three results as + is \verb+_N+ + \item \verb+%hist [-n]+ macro shows previous history, \verb+-n+ + suppresses line number information + \end{itemize} + \item Log the session using \verb+%logstart+, \verb+%logon+ and + \verb+%logoff+ + \item \verb+%run [options] file[.py]+ -- running Python code + \begin{itemize} + \item \verb+%run -d [-b<N>]+: debug script with pdb + \verb+N+ is the line number to break at (defaults to 1) + \item \verb+%run -t+: time the script + \item \verb+%run -p+: Profile the script + \end{itemize} + \item \verb+%prun+ runs a statement/expression under the profiler + \item \verb+%macro [options] macro_name n1-n2 n3-n4 n6+ save specified + lines to a macro with name \verb+macro_name+ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features \ldots} + \begin{itemize} + \item \verb+%edit [options] [args]+: edit lines of code or file + specified in editor (configure editor via \verb+$EDITOR+) + \item \verb+%cd+ changes directory, see also \verb+%pushd, %popd, %dhist+ + \item Shell access + \begin{itemize} + \item \verb+!command+ runs a shell command and returns its output + \item \verb+files = %sx ls+ or \verb+files = !ls+ sets + \verb+files+ to all result of the \verb+ls+ command + \item \verb+%sx+ is quiet + \item \verb+!ls $files+ passes the \verb+files+ variable to the + shell command + \item \verb+%alias alias_name cmd+ creates an alias for a system + command + \end{itemize} + \item \verb+%colors+ lets you change the color scheme to + \verb+NoColor, Linux, LightBG+ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More IPython features \ldots} + \begin{itemize} + \item Use \verb+;+ at the end of a statement to suppress printing + output + \item \verb+%bookmark+: store a bookmarked location, for use with \verb+%cd+ + \item \verb+%who, %whos+: print information on variables + \item \verb+%save [options] filename n1-n2 n3-n4+: save lines to a + file + \item \verb+%time statement+: Time execution of a Python statement or + expression + \item \verb+%timeit [-n<N> -r<R> [-t|-c]] statement+: time execution + using Python's timeit module + \item Can define and use profiles to setup IPython differently: + \verb+math, scipy, numeric, pysh+ etc. + \item \verb+%magic+: \alert{Show help on all magics} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{File handling} +\begin{lstlisting} +>>> # Reading files: +... f = open('/path/to/file_name') +>>> data = f.read() # Read entire file. +>>> line = f.readline() # Read one line. +>>> # Read entire file appending each line into a list +... lines = f.readlines() +>>> f.close() # close the file. +>>> # Writing files: +... f = open('/path/to/file_name', 'w') +>>> f.write('hello world\n') +\end{lstlisting} + \begin{itemize} + \item \typ{tell()}: returns int of current position + \item \typ{seek(pos)}: moves current position to specified byte + \item Call \typ{close()} when done using a file + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Math} + \begin{itemize} + \item \typ{math} module provides basic math routines for + floats + \item \typ{cmath} module provides math routies for complex + numbers + \item \typ{random}: provides pseudo-random number generators + for various distributions + \item These are always available and part of the standard library + \item More serious math is provided by the NumPy/SciPy modules -- + these are not standard and need to be installed separately + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Timing and profiling} + \begin{itemize} + \item Timing code: use the \typ{time} module + \item Read up on \typ{time.time()} and \typ{time.clock()} + \item \typ{timeit}: is a better way of doing timing + \item IPython has handy \typ{time} and \typ{timeit} macros (type + \typ{timeit?} for help) + \item IPython lets you debug and profile code via the \typ{run} + macro (type \typ{run?} on the prompt to learn more) + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item \typ{dir([object])} function: attributes of given object + \item \typ{type(object)}: returns type information + \item \typ{str(), repr()}: convert object to string representation + \item \typ{isinstance, issubclass} + \item \typ{assert} statements let you do debugging assertions in + code + \item \typ{csv} module: reading and writing CSV files + \item \typ{pickle}: lets you save and load Python objects + (\alert{serialization}) + \item \typ{sys.argv}: command line arguments + \item \typ{os.path}: common path manipulations + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Test driven development (TDD)} + \begin{itemize} + \item Why? + \begin{itemize} + + \item Forces you to write reusable code! + + \item Think about the API + + \item More robust + + \item Makes refactoring very easy + + \end{itemize} + \item How? Python offers three major ways of doing this + \begin{itemize} + \item doctest + \item unittest + \item nosetest (and similar like py.test) + \end{itemize} + + \item Test every piece of functionality you offer + + \item This isn't a formal introduction but more a practical one + + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Unit test} +\begin{lstlisting} +import unittest + +class MyTestCase(unittest.TestCase): + def setUp(self): + # Called *before* each test_* + def tearDown(self): + # Called *after* each test_* + def test_something(self): + "docstring" + # Test code. + self.assertEqual(x, y) + self.assertRaises(ValueError, func, arg1, arg2 ...) + +if __name__ == '__main__': + unittest.main() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Nosetest} +\begin{lstlisting} +import particle +def test_particle(): + # Use asserts here. + p = particle.Particle(1.0) + assert p.property[0] == 1.0 + assert p.property[2] == 0.0 + +if __name__ == '__main__': + import nose + nose.main() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Testing} + \begin{itemize} + \item More details: see library reference and search for nosetest + \end{itemize} +\end{frame} + +\section{Numerics \& Plotting} + +\subsection{NumPy Arrays} + +\newcommand{\num}{\texttt{numpy}} + +\begin{frame} + \frametitle{The \num\ module} + \begin{itemize} + \item Manipulating large Python lists for scientific computing is + \alert{slow} + \item Most complex computations can be reduced to a few standard + operations + \item The \num\ module provides: + \begin{itemize} + \item An efficient and powerful array type for various common data + types + \item Abstracts out the most commonly used standard operations on + arrays + \end{itemize} + \item Numeric was the first, then came \texttt{numarray}. + \texttt{numpy} is the latest and is the future + \item This course uses \num\ and only covers the absolute basics + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Basic concepts} + \begin{itemize} + \item \num\ arrays are of a fixed size (\typ{arr.size}) and have the + same type (\typ{arr.dtype}) + \item \num\ arrays may have arbitrary dimensionality + \item The \typ{shape} of an array is the extent (length) of the + array along each dimension + \item The \typ{rank(arr)} of an array is the ``dimensionality'' of the + array + \item The \typ{arr.itemsize} is the number of bytes (8-bits) used for + each element of the array + \item \alert{Note:} The \typ{shape} and \typ{rank} may change as + long as the \typ{size} of the array is fixed + \item \alert{Note:} \typ{len(arr) != arr.size} in general + \item \alert{Note:} By default array operations are performed + \alert{elementwise} + \item Indices start from 0 + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Examples of \num} +\begin{lstlisting} +# Simple array math example +>>> from numpy import * +>>> a = array([1,2,3,4]) +>>> b = array([2,3,4,5]) +>>> a + b # Element wise addition! +array([3, 5, 7, 9]) + +>>> print pi, e # Pi and e are defined. +3.14159265359 2.71828182846 +# Create array from 0 to 10 +>>> x = arange(0.0, 10.0, 0.05) +>>> x *= 2*pi/10 # multiply array by scalar value +array([ 0.,0.0314,...,6.252]) +# apply functions to array. +>>> y = sin(x) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{More examples of \num} +\vspace*{-8pt} +\begin{lstlisting} +# Size, shape, rank, type etc. +>>> x = array([1., 2, 3, 4]) +>>> size(x) +4 +>>> x.dtype # or x.dtype.char +'d' +>>> x.shape +(4,) +>>> print rank(x), x.itemsize +1 8 +>>> x.tolist() +[1.0, 2.0, 3.0, 4.0] +# Array indexing +>>> x[0] = 10 +>>> print x[0], x[-1] +10.0 4.0 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Multi-dimensional arrays} +\begin{lstlisting} +>>> a = array([[ 0, 1, 2, 3], +... [10,11,12,13]]) +>>> a.shape # (rows, columns) +(2, 4) +# Accessing and setting values +>>> a[1,3] +13 +>>> a[1,3] = -1 +>>> a[1] # The second row +array([10,11,12,-1]) + +# Flatten/ravel arrays to 1D arrays +>>> a.flat # or ravel(a) +array([0,1,2,3,10,11,12,-1]) +# Note: flat references original memory +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Slicing arrays} +\begin{lstlisting} +>>> a = array([[1,2,3], [4,5,6], [7,8,9]]) +>>> a[0,1:3] +array([2, 3]) +>>> a[1:,1:] +array([[5, 6], + [8, 9]]) +>>> a[:,2] +array([3, 6, 9]) +# Striding... +>>> a[0::2,0::2] +array([[1, 3], + [7, 9]]) +# All these slices are references to the same memory! +\end{lstlisting} +\end{frame} + +% \begin{frame}[fragile] +% \frametitle{Array types and typecodes} +% \begin{tabular}[c]{|c|c|p{2.75in}|} +% \hline +% Character & Bits (bytes) & Type name \\ +% \hline +% D & 128 (16) & \typ{Complex, Complex64}\\ +% F & 64 (8) & \typ{Complex0, Complex8, Complex16} \\ +% d & 64 (8) & \typ{Float, Float64} \\ +% f & 32 (4) & \typ{Float0, Float8, Float16} \\ +% i & 32 (4) & \typ{Int32} \\ +% l & 32 (4) & \typ{Int} \\ +% O & 4 (1) & \typ{PyObject} \\ +% %b 8 (1) UnsignedInt8 +% %1 (one) 8 (1) Int8 +% %s 16 (2) Int16 +% \hline +% \end{tabular} +% \begin{lstlisting} +% # Examples +% >>> f = array([1,2,3], Float32) +% >>> c = array([1,2,3], Complex32) +% >>> print f, c +% [ 1. 2. 3.] [ 1.+0.j 2.+0.j 3.+0.j] +% \end{lstlisting} +% \end{frame} + +\begin{frame}[fragile] + \frametitle{Array creation functions} + \begin{itemize} + \item \typ{array(object, dtype=None, copy=1,order=None, subok=0,ndmin=0)} + \item \typ{arange(start, stop=None, step=1, dtype=None)} + \item \typ{linspace(start, stop, num=50, endpoint=True, retstep=False)} + \item \typ{ones(shape, dtype=None, order='C')} + \item \typ{zeros((d1,...,dn),dtype=float,order='C')} + \item \typ{identity(n)} + \item \typ{empty((d1,...,dn),dtype=float,order='C')} + \item \typ{ones\_like(x)}, \typ{zeros\_like(x)}, \typ{empty\_like(x)} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Array math} + \begin{itemize} + \item Basic \alert{elementwise} math (given two arrays \typ{a, b}): + \begin{itemize} + \item \typ{a + b $\rightarrow$ add(a, b)} + \item \typ{a - b, $\rightarrow$ subtract(a, b)} + \item \typ{a * b, $\rightarrow$ multiply(a, b)} + \item \typ{a / b, $\rightarrow$ divide(a, b)} + \item \typ{a \% b, $\rightarrow$ remainder(a, b)} + \item \typ{a ** b, $\rightarrow$ power(a, b)} + \end{itemize} + \item Inplace operators: \typ{a += b}, or \typ{add(a, b, + a)} etc. + \item Logical operations: \typ{equal (==)}, \typ{not\_equal (!=)}, + \typ{less (<)}, \typ{greater (>)} etc. + \item Trig and other functions: \typ{sin(x), arcsin(x), sinh(x), + exp(x), sqrt(x)} etc. + \item \typ{sum(x, axis=0), product(x, axis=0)}: sum and product of array elements + \item \typ{dot(a, b)} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Advanced} + \begin{itemize} + \item Only scratched the surface of \num + \item Ufunc methods: \typ{reduce, accumulate, outer, reduceat} + \item Typecasting + \item More functions: \typ{take, choose, where, compress, + concatenate} + \item Array broadcasting and \typ{None} + \end{itemize} +\end{frame} + +\subsection{Plotting: Matplotlib} + +\begin{frame} + \frametitle{About \texttt{matplotlib}} + \begin{itemize} + \item Easy to use, scriptable, ``Matlab-like'' 2D plotting + \item Publication quality figures and interactive capabilities + \item Plots, histograms, power spectra, bar charts, errorcharts, + scatterplots, etc. + \item Also does polar plots, maps, contours + \item Support for simple \TeX\ markup + \item Multiple output backends (images, EPS, SVG, wx, Agg, Tk, GTK) + \item Cross-platform: Linux, Win32, Mac OS X + \item Good idea to use via IPython: \typ{ipython -pylab} + \item From scripts use: \typ{import pylab} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{More information} + \begin{itemize} + \item More information here: \url{http://matplotlib.sf.net} + \item \url{http://matplotlib.sf.net/tutorial.html} + \item \url{http://matplotlib.sf.net/screenshots.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting with \texttt{matplotlib}} +\begin{lstlisting} +>>> x = arange(0, 2*pi, 0.05) +>>> plot(x, sin(x)) # Same as plot(x, sin(x), 'b-') +>>> plot(x, sin(x), 'ro') +>>> axis([0,2*pi, -1,1]) +>>> xlabel(r'$\chi$', color='g') +>>> ylabel(r'sin($\chi$)', color='r') +>>> title('A simple figure', fontsize=20) +>>> savefig('/tmp/test.eps') +# Multiple plots in one figure +>>> t = arange(0.0, 5.2, 0.2) +# red dashes, blue squares and green triangles +>>> plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting \ldots} +\begin{lstlisting} +# Set properties of objects: +>>> plot(x, sin(x), linewidth=2.0, color='r') +>>> l, = plot(x, sin(x)) +>>> setp(l, linewidth=2.0, color='r') +>>> l.set_linewidth(2.0); l.set_color('r') +>>> draw() # Redraws current figure. +>>> setp(l) # Prints available properties +>>> close() # Closes the figure. +# Multiple figures: +>>> figure(1); plot(x, sin(x)) +>>> figure(2); plot(x, tanh(x)) +>>> figure(1); title('Easy as 1,2,3') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic plotting \ldots} +\begin{lstlisting} +>>> figure(1) +>>> subplot(211) # Same as subplot(2, 1, 1) +>>> plot(x, cos(5*x)*exp(-x)) +>>> subplot(2, 1, 2) +>>> plot(x, cos(5*x), 'r--', label='cosine') +>>> plot(x, sin(5*x), 'g--', label='sine') +>>> legend() # Or legend(['cosine', 'sine']) +>>> text(1,0, '(1,0)') +>>> axes = gca() # Current axis +>>> fig = gcf() # Current figure +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{X-Y plot} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/xyplot} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +t1 = arange(0.0, 5.0, 0.1) +t2 = arange(0.0, 5.0, 0.02) +t3 = arange(0.0, 2.0, 0.01) +subplot(211) +plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', + t2, cos(2*pi*t2)*exp(-t2), 'k') +grid(True) +title('A tale of 2 subplots') +ylabel('Damped') +subplot(212) +plot(t3, cos(2*pi*t3), 'r--') +grid(True) +xlabel('time (s)') +ylabel('Undamped') +\end{lstlisting} + \end{block} + \end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Errorbar} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/errorbar} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +t = arange(0.1, 4, 0.1) +s = exp(-t) +e = 0.1*abs(randn(len(s))) +f = 0.1*abs(randn(len(s))) +g = 2*e +h = 2*f +errorbar(t, s, [e,g], f, fmt='o') +xlabel('Distance (m)') +ylabel('Height (m)') +title('Mean and standard error '\ + 'as a function of distance') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Semi-log and log-log plots} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/log} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +dt = 0.01 +t = arange(dt, 20.0, dt) +subplot(311) +semilogy(t, exp(-t/5.0)) +ylabel('semilogy') +grid(True) +subplot(312) +semilogx(t, sin(2*pi*t)) +ylabel('semilogx') +grid(True) +# minor grid on too +gca().xaxis.grid(True, which='minor') +subplot(313) +loglog(t, 20*exp(-t/10.0), basex=4) +grid(True) +ylabel('loglog base 4 on x') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Histogram} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/histogram} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +mu, sigma = 100, 15 +x = mu + sigma*randn(10000) +# the histogram of the data +n, bins, patches = hist(x, 100, normed=1) +# add a 'best fit' line +y = normpdf( bins, mu, sigma) +l = plot(bins, y, 'r--', linewidth=2) +xlim(40, 160) +xlabel('Smarts') +ylabel('P') +title(r'$\rm{IQ:}\/ \mu=100,\/ \sigma=15$') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Bar charts} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/barchart} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +N = 5 +menMeans = (20, 35, 30, 35, 27) +menStd = ( 2, 3, 4, 1, 2) +# the x locations for the groups +ind = arange(N) +# the width of the bars +width = 0.35 +p1 = bar(ind, menMeans, width, + color='r', yerr=menStd) +womenMeans = (25, 32, 34, 20, 25) +womenStd = ( 3, 5, 2, 3, 3) +p2 = bar(ind+width, womenMeans, width, + color='y', yerr=womenStd) +ylabel('Scores') +title('Scores by group and gender') +xticks(ind+width, + ('G1', 'G2', 'G3', 'G4', 'G5')) +xlim(-width,len(ind)) +yticks(arange(0,41,10)) +legend((p1[0], p2[0]), + ('Men', 'Women'), shadow=True) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Pie charts} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.4in} + \includegraphics[height=2.0in, interpolate=true]{data/piechart} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +# make a square figure and axes +figure(1, figsize=(8,8)) +ax = axes([0.1, 0.1, 0.8, 0.8]) +labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' +fracs = [15,30,45, 10] +explode=(0, 0.05, 0, 0) +pie(fracs, explode=explode, labels=labels, + autopct='%1.1f%%', shadow=True) +title('Raining Hogs and Dogs', + bbox={'facecolor':'0.8', 'pad':5}) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Scatter plots} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.4in} + \includegraphics[height=2in, interpolate=true]{data/scatter} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +N = 30 +x = 0.9*rand(N) +y = 0.9*rand(N) +# 0 to 10 point radiuses +area = pi*(10 * rand(N))**2 +volume = 400 + rand(N)*450 +scatter(x,y,s=area, marker='o', c=volume, + alpha=0.75) +xlabel(r'$\Delta_i$', size='x-large') +ylabel(r'$\Delta_{i+1}$', size='x-large') +title(r'Volume and percent change') +grid(True) +colorbar() +savefig('scatter') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Polar} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/polar} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +figure(figsize=(8,8)) +ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, + axisbg='#d5de9c') +r = arange(0,1,0.001) +theta = 2*2*pi*r +polar(theta, r, color='#ee8d18', lw=3) +# the radius of the grid labels +setp(ax.thetagridlabels, y=1.075) +title(r"$\theta=4\pi r", fontsize=20) +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Contours} + \begin{columns} + \column{0.45\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/contour} + \column{0.525\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +x = arange(-3.0, 3.0, 0.025) +y = arange(-2.0, 2.0, 0.025) +X, Y = meshgrid(x, y) +Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) +Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) +# difference of Gaussians +Z = 10.0 * (Z2 - Z1) +im = imshow(Z, interpolation='bilinear', + origin='lower', + cmap=cm.gray, extent=(-3,3,-2,2)) +levels = arange(-1.2, 1.6, 0.2) +# label every second level +clabel(CS, levels[1::2], inline=1, + fmt='%1.1f', fontsize=14) +CS = contour(Z, levels, + origin='lower', + linewidths=2, + extent=(-3,3,-2,2)) +# make a colorbar for the contour lines +CB = colorbar(CS, shrink=0.8, extend='both') +title('Lines with colorbar') +hot(); flag() +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Velocity vectors} + \begin{columns} + \column{0.5\textwidth} + \hspace*{-0.5in} + \includegraphics[height=2in, interpolate=true]{data/quiver} + \column{0.45\textwidth} + \begin{block}{Example code} + \tiny +\begin{lstlisting} +X,Y = meshgrid(arange(0,2*pi,.2), + arange(0,2*pi,.2) ) +U = cos(X) +V = sin(Y) +Q = quiver(X[::3, ::3], Y[::3, ::3], + U[::3, ::3], V[::3, ::3], + color='r', units='x', + linewidths=(2,), + edgecolors=('k'), + headaxislength=5 ) +qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', + fontproperties= + {'weight': 'bold'}) +axis([-1, 7, -1, 7]) +title('triangular head; scale '\ + 'with x view; black edges') +\end{lstlisting} + \end{block} +\end{columns} +\end{frame} + +\begin{frame}[fragile] \frametitle{Maps} + \includegraphics[height=2.5in, interpolate=true]{data/plotmap} + \begin{center} + \tiny + For details see \url{http://matplotlib.sourceforge.net/screenshots/plotmap.py} + \end{center} +\end{frame} + + +\subsection{SciPy} + +\begin{frame} + \frametitle{Using \texttt{SciPy}} + \begin{itemize} + \item SciPy is Open Source software for mathematics, science, and + engineering + \item \typ{import scipy} + \item Built on NumPy + \item Provides modules for statistics, optimization, integration, + linear algebra, Fourier transforms, signal and image processing, + genetic algorithms, ODE solvers, special functions, and more + \item Used widely by scientists world over + \item Details are beyond the scope of this tutorial + \end{itemize} +\end{frame} + +\section{Standard library} + +\subsection{Quick Tour} + +\begin{frame} + \frametitle{Standard library} + \begin{itemize} + \item Very powerful + \item ``Batteries included'' + \item Example standard modules taken from the tutorial + \begin{itemize} + \item Operating system interface: \typ{os} + \item System, Command line arguments: \typ{sys} + \item Regular expressions: \typ{re} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib2}, \typ{smtplib} + \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, + \typ{zipfile}, and \typ{tarfile} + \item Unit testing: \typ{doctest} and \typ{unittest} + \item And a whole lot more! + \end{itemize} + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import os +>>> os.system('date') +Fri Jun 10 22:13:09 IST 2005 +0 +>>> os.getcwd() +'/home/prabhu' +>>> os.chdir('/tmp') +>>> import os +>>> dir(os) +<returns a list of all module functions> +>>> help(os) +<extensive manual page from module's docstrings> +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import sys +>>> # Print the list of command line args to Python +... print sys.argv +[''] +>>> import re # Regular expressions +>>> re.findall(r'\bf[a-z]*', +... 'which foot or hand fell fastest') +['foot', 'fell', 'fastest'] +>>> re.sub(r'(\b[a-z]+) \1', r'\1', +... 'cat in the the hat') +'cat in the hat' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import math +>>> math.cos(math.pi / 4.0) +0.70710678118654757 +>>> math.log(1024, 2) +10.0 +>>> import random +>>> random.choice(['apple', 'pear', 'banana']) +'pear' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import urllib2 +>>> f = urllib2.urlopen('http://www.python.org/') +>>> print f.read(100) +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<?xml-stylesheet href="./css/ht2html +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stdlib: examples} +\begin{lstlisting} +>>> import zlib +>>> s = 'witch which has which witches wrist watch' +>>> len(s) +41 +>>> t = zlib.compress(s) +>>> len(t) +37 +>>> zlib.decompress(t) +'witch which has which witches wrist watch' +>>> zlib.crc32(t) +-1438085031 +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Introduced Python + \item Basic syntax + \item Basic types and data structures + \item Control flow + \item Functions + \item Modules + \item Exceptions + \item Classes + \item Standard library + \end{itemize} +\end{frame} + +\end{document} + +\subsection{Basic data structures} +\begin{frame}{Lists} + \begin{itemize} + \item \texttt{species = [ 'humans', 'orcs', 'elves', 'dwarves' ]} + \item \texttt{ ids = [ 107, 109, 124, 141, 142, 144 ]} + \item \texttt{ oneliners = [ 'I will be back', 'Do or do not! No try!!', 42 ] } + \end{itemize} + + \begin{block}{List operations} + ids + [ 100, 102 ]\\ + species.append( 'unicorns')\\ + print oneliners[ 1 ]\\ + look up \alert{docs.python.org/tutorial/datastructures.html} + \end{block} +\end{frame} +\end{document} +\section{Python Tutorial} +\subsection{Preliminaries} +\begin{frame} + \frametitle{Using the interpreter} + \begin{itemize} + \item Starting up: \typ{python} or \typ{ipython} + \item Quitting: \typ{Control-D} or \typ{Control-Z} (on Win32) + \item Can use it like a calculator + \item Can execute one-liners via the \typ{-c} option: + \typ{python -c "print 'hello world'"} + \item Other options via \typ{python -h} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{IPython} + \begin{itemize} + \item Recommended interpreter, IPython: + \url{http://ipython.scipy.org} + \item Better than the default Python shell + \item Supports tab completion by default + \item Easier object introspection + \item Shell access! + \item Command system to allow extending its own behavior + \item Supports history (across sessions) and logging + \item Can be embedded in your own Python code + \item Support for macros + \item A flexible framework for your own custom interpreter + \item Other miscellaneous conveniences + \item We'll get back to this later + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Basic IPython features} + \begin{itemize} + \item Startup: \verb+ipython [options] files+ + \begin{itemize} + \item \verb+ipython [-wthread|-gthread|-qthread]+: + Threading modes to support wxPython, pyGTK and Qt + \item \verb+ipython -pylab+: Support for matplotlib + \end{itemize} + \item TAB completion: + \begin{itemize} + \item Type \verb+object_name.<TAB>+ to see list of options + \item Also completes on file and directory names + \end{itemize} + \item \verb+object?+ shows docstring/help for any Python object + \item \verb+object??+ presents more docs (and source if possible) + \item Debugging with \verb+%pdb+ magic: pops up pdb on errors + \item Access history (saved over earlier sessions also) + \begin{itemize} + \item Use \texttt{<UpArrow>}: move up history + \item Use \texttt{<Ctrl-r> string}: search history backwards + \item Use \texttt{Esc >}: get back to end of history + \end{itemize} + \item \verb+%run [options] file[.py]+ lets you run Python code + \end{itemize} +\end{frame} +% LocalWords: BDFL Guido Rossum PSF Nokia OO Zope CMS RedHat SciPy MayaVi spam +% LocalWords: IPython ipython stdin TypeError dict int elif PYTHONPATH IOError +% LocalWords: namespace Namespaces SyntaxError ZeroDivisionError NameError str +% LocalWords: ValueError subclassed def + + + \item Types are of two kinds: \alert{mutable} and \alert{immutable} + \item Immutable types: numbers, strings, \typ{None} and tuples + \item Immutables cannot be changed ``in-place'' + \item Mutable types: lists, dictionaries, instances, etc. + \item Mutable objects can be ``changed'' + \end{itemize} + + +\begin{frame} + \frametitle{Important!} + \begin{itemize} + \item Assignment to an object is by reference + \item Essentially, \alert{names are bound to objects} + \end{itemize} +\end{frame} + + +\end{document} +\begin{frame}[fragile] + \frametitle{Dictionaries} + \begin{itemize} + \item Associative arrays/mappings + \item Indexed by ``keys'' (keys must be immutable) + \item \typ{dict[key] = value} + \item \typ{keys()} returns all keys of the dict + \item \typ{values()} returns the values of the dict + \item \verb+has_key(key)+ returns if \typ{key} is in the dict + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries: example} + \begin{lstlisting} +>>> tel = {'jack': 4098, 'sape': 4139} +>>> tel['guido'] = 4127 +>>> tel +{'sape': 4139, 'guido': 4127, 'jack': 4098} +>>> tel['jack'] +4098 +>>> del tel['sape'] +>>> tel['irv'] = 4127 +>>> tel +{'guido': 4127, 'irv': 4127, 'jack': 4098} +>>> tel.keys() +['guido', 'irv', 'jack'] +>>> tel.has_key('guido') +True + \end{lstlisting} +\end{frame} + +\subsection{Control flow, functions} + + + +\begin{frame}[fragile] + \frametitle{\typ{If} example} + \begin{lstlisting} +>>> a = ['cat', 'window', 'defenestrate'] +>>> if 'cat' in a: +... print "meaw" +... +meaw +>>> pets = {'cat': 1, 'dog':2, 'croc': 10} +>>> if 'croc' in pets: +... print pets['croc'] +... +10 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for} example} + \begin{lstlisting} +>>> a = ['cat', 'window', 'defenestrate'] +>>> for x in a: +... print x, len(x) +... +cat 3 +window 6 +defenestrate 12 +>>> knights = {'gallahad': 'the pure', +... 'robin': 'the brave'} +>>> for k, v in knights.iteritems(): +... print k, v +... +gallahad the pure +robin the brave +\end{lstlisting} +\end{frame} |