1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Tutorial slides on Python.
%
% Author: Prabhu Ramachandran <prabhu at aero.iitb.ac.in>
% Copyright (c) 2005-2009, 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, October 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}
\section{Python}
\subsection{Exercises on Control flow}
\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}
\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}
|