|
1 \documentclass[12pt]{article} |
|
2 \title{Python Workshop\\Problems and Exercises} |
|
3 \author{Asokan Pichai\\Prabhu Ramachandran} |
|
4 \begin{document} |
|
5 \maketitle |
|
6 |
|
7 \section{Python} |
|
8 \subsection{Getting started} |
|
9 \begin{verbatim} |
|
10 >>> print 'Hello Python' |
|
11 >>> print 3124 * 126789 |
|
12 >>> 1786 % 12 |
|
13 >>> 3124 * 126789 |
|
14 >>> a = 3124 * 126789 |
|
15 >>> big = 12345678901234567890 ** 3 |
|
16 >>> verybig = big * big * big * big |
|
17 >>> 12345**6, 12345**67, 12345**678 |
|
18 |
|
19 >>> s = 'Hello ' |
|
20 >>> p = 'World' |
|
21 >>> s + p |
|
22 >>> s * 12 |
|
23 >>> s * s |
|
24 >>> s + p * 12, (s + p)* 12 |
|
25 >>> s * 12 + p * 12 |
|
26 >>> 12 * s |
|
27 \end{verbatim} |
|
28 \newpage |
|
29 |
|
30 \begin{verbatim} |
|
31 >>> 17/2 |
|
32 >>> 17/2.0 |
|
33 >>> 17.0/2 |
|
34 >>> 17.0/8.5 |
|
35 >>> int(17/2.0) |
|
36 >>> float(17/2) |
|
37 >>> str(17/2.0) |
|
38 >>> round( 7.5 ) |
|
39 \end{verbatim} |
|
40 |
|
41 \subsection{Mini exercises} |
|
42 \begin{itemize} |
|
43 \item Round a float to the nearest integer, using \texttt{int()}? |
|
44 \item What does this do? \\\texttt{round(amount * 10) /10.0 } |
|
45 \item How to round a number to the nearest 5 paise? |
|
46 \begin{description} |
|
47 \item[Remember] 17.23 $\rightarrow$ 17.25,\\ while 17.22 $\rightarrow$ 17.20 |
|
48 \end{description} |
|
49 \item How to round a number to the nearest 20 paise? |
|
50 \end{itemize} |
|
51 |
|
52 \begin{verbatim} |
|
53 amount = 12.68 |
|
54 denom = 0.05 |
|
55 nCoins = round(amount/denom) |
|
56 rAmount = nCoins * denom |
|
57 \end{verbatim} |
|
58 |
|
59 \subsection{Dynamic typing} |
|
60 \begin{verbatim} |
|
61 a = 1 |
|
62 a = 1.1 |
|
63 a = "Now I am a string!" |
|
64 \end{verbatim} |
|
65 |
|
66 \subsection{Comments} |
|
67 \begin{verbatim} |
|
68 a = 1 # In-line comments |
|
69 # Comment in a line to itself. |
|
70 a = "# This is not a comment!" |
|
71 \end{verbatim} |
|
72 |
|
73 \section{Data types} |
|
74 \subsection{Numbers} |
|
75 \begin{verbatim} |
|
76 >>> a = 1 # Int. |
|
77 >>> l = 1000000L # Long |
|
78 >>> e = 1.01325e5 # float |
|
79 >>> f = 3.14159 # float |
|
80 >>> c = 1+1j # Complex! |
|
81 >>> print f*c/a |
|
82 (3.14159+3.14159j) |
|
83 >>> print c.real, c.imag |
|
84 1.0 1.0 |
|
85 >>> abs(c) |
|
86 1.4142135623730951 |
|
87 >>> abs( 8 - 9.5 ) |
|
88 1.5 |
|
89 \end{verbatim} |
|
90 |
|
91 \subsection{Boolean} |
|
92 \begin{verbatim} |
|
93 >>> t = True |
|
94 >>> f = not t |
|
95 False |
|
96 >>> f or t |
|
97 True |
|
98 >>> f and t |
|
99 False |
|
100 >>> NOT True |
|
101 \ldots ??? |
|
102 >>> not TRUE |
|
103 \ldots ??? |
|
104 \end{verbatim} |
|
105 |
|
106 \subsection{Relational and logical operators} |
|
107 \begin{verbatim} |
|
108 >>> a, b, c = -1, 0, 1 |
|
109 >>> a == b |
|
110 False |
|
111 >>> a <= b |
|
112 True |
|
113 >>> a + b != c |
|
114 True |
|
115 >>> a < b < c |
|
116 True |
|
117 >>> c >= a + b |
|
118 True |
|
119 \end{verbatim} |
|
120 |
|
121 \subsection{Strings} |
|
122 \begin{verbatim} |
|
123 s = 'this is a string' |
|
124 s = 'This one has "quotes" inside!' |
|
125 s = "I have 'single-quotes' inside!" |
|
126 l = "A string spanning many lines\ |
|
127 one more line\ |
|
128 yet another" |
|
129 t = """A triple quoted string does |
|
130 not need to be escaped at the end and |
|
131 "can have nested quotes" etc.""" |
|
132 \end{verbatim} |
|
133 |
|
134 \begin{verbatim} |
|
135 >>> w = "hello" |
|
136 >>> print w[0] + w[2] + w[-1] |
|
137 hlo |
|
138 >>> len(w) # guess what |
|
139 5 |
|
140 >>> s = u'Unicode strings!' |
|
141 >>> # Raw strings (note the leading 'r') |
|
142 ... r_s = r'A string $\alpha \nu$' |
|
143 \end{verbatim} |
|
144 \begin{verbatim} |
|
145 >>> w[0] = 'H' # Can't do that! |
|
146 Traceback (most recent call last): |
|
147 File "<stdin>", line 1, in ? |
|
148 TypeError: object does not support item assignment |
|
149 \end{verbatim} |
|
150 |
|
151 \subsection{IPython} |
|
152 \begin{verbatim} |
|
153 In [1]: a = 'hello world' |
|
154 In [2]: a.startswith('hell') |
|
155 Out[2]: True |
|
156 In [3]: a.endswith('ld') |
|
157 Out[3]: True |
|
158 In [4]: a.upper() |
|
159 Out[4]: 'HELLO WORLD' |
|
160 In [5]: a.upper().lower() |
|
161 Out[5]: 'hello world' |
|
162 |
|
163 In [6]: a.split() |
|
164 Out[6]: ['hello', 'world'] |
|
165 In [7]: ''.join(['a', 'b', 'c']) |
|
166 Out[7]: 'abc' |
|
167 In [8] 'd' in ''.join( 'a', 'b', 'c') |
|
168 Out[8]: False |
|
169 a.split( 'o' )} |
|
170 ??? |
|
171 'x'.join( a.split( 'o' ) ) |
|
172 ??? |
|
173 |
|
174 In [11]: x, y = 1, 1.2 |
|
175 In [12]: 'x is %s, y is %s' %(x, y) |
|
176 Out[12]: 'x is 1, y is 1.234' |
|
177 |
|
178 'x is \%d, y is \%f' \%(x, y) |
|
179 ??? |
|
180 'x is \%3d, y is \%4.2f' \%(x, y) |
|
181 ??? |
|
182 \end{verbatim} |
|
183 |
|
184 \subsection{A classic problem} |
|
185 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! |
|
186 |
|
187 \subsection{Basic conditional flow} |
|
188 \begin{verbatim} |
|
189 In [21]: a = 7 |
|
190 In [22]: b = 8 |
|
191 In [23]: if a > b: |
|
192 ....: print 'Hello' |
|
193 ....: else: |
|
194 ....: print 'World' |
|
195 ....: |
|
196 ....: |
|
197 World |
|
198 \end{verbatim} |
|
199 |
|
200 \subsection{\texttt{If...elif...else} example} |
|
201 \begin{verbatim} |
|
202 x = int(raw_input("Enter an integer:")) |
|
203 if x < 0: |
|
204 print 'Be positive!' |
|
205 elif x == 0: |
|
206 print 'Zero' |
|
207 elif x == 1: |
|
208 print 'Single' |
|
209 else: |
|
210 print 'More' |
|
211 \end{verbatim} |
|
212 |
|
213 \subsection{Basic looping} |
|
214 \begin{verbatim} |
|
215 # Fibonacci series: |
|
216 # the sum of two elements |
|
217 # defines the next |
|
218 a, b = 0, 1 |
|
219 while b < 10: |
|
220 print b, |
|
221 a, b = b, a + b |
|
222 |
|
223 \end{verbatim} |
|
224 |
|
225 \section{Problem set 1} |
|
226 All the problems can be solved using \texttt{if} and \texttt{while} |
|
227 \begin{description} |
|
228 \item[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$\\ |
|
229 These are called $Armstrong$ numbers. |
|
230 |
|
231 \item[1.2 Collatz sequence] |
|
232 \begin{enumerate} |
|
233 \item Start with an arbitrary (positive) integer. |
|
234 \item If the number is even, divide by 2; if the number is odd multiply by 3 and add 1. |
|
235 \item Repeat the procedure with the new number. |
|
236 \item There is a cycle of 4, 2, 1 at which the procedure loops. |
|
237 \end{enumerate} |
|
238 Write a program that accepts the starting value and prints out the Collatz sequence. |
|
239 |
|
240 \item[1.3] |
|
241 Write a program that prints the following pyramid on the screen. |
|
242 \begin{verbatim} |
|
243 1 |
|
244 2 2 |
|
245 3 3 3 |
|
246 4 4 4 4 |
|
247 \end{verbatim} |
|
248 The number of lines must be obtained from the user as input.\\ |
|
249 When can your code fail? |
|
250 \end{description} |
|
251 |
|
252 \subsection{Functions: examples} |
|
253 \begin{verbatim} |
|
254 def signum( r ): |
|
255 """returns 0 if r is zero |
|
256 -1 if r is negative |
|
257 +1 if r is positive""" |
|
258 if r < 0: |
|
259 return -1 |
|
260 elif r > 0: |
|
261 return 1 |
|
262 else: |
|
263 return 0 |
|
264 |
|
265 def pad( n, size ): |
|
266 """pads integer n with spaces |
|
267 into a string of length size |
|
268 """ |
|
269 SPACE = ' ' |
|
270 s = str( n ) |
|
271 padSize = size - len( s ) |
|
272 return padSize * SPACE + s |
|
273 \end{verbatim} |
|
274 What about \%3d? |
|
275 |
|
276 \subsection {What does this function do?} |
|
277 \begin{verbatim} |
|
278 def what( n ): |
|
279 if n < 0: n = -n |
|
280 while n > 0: |
|
281 if n % 2 == 1: |
|
282 return False |
|
283 n /= 10 |
|
284 return True |
|
285 \end{verbatim} |
|
286 \newpage |
|
287 |
|
288 \subsection{What does this function do?} |
|
289 \begin{verbatim} |
|
290 def what( n ): |
|
291 i = 1 |
|
292 while i * i < n: |
|
293 i += 1 |
|
294 return i * i == n, i |
|
295 \end{verbatim} |
|
296 |
|
297 \subsection{What does this function do?} |
|
298 \begin{verbatim} |
|
299 def what( n, x ): |
|
300 z = 1.0 |
|
301 if n < 0: |
|
302 x = 1.0 / x |
|
303 n = -n |
|
304 while n > 0: |
|
305 if n % 2 == 1: |
|
306 z *= x |
|
307 n /= 2 |
|
308 x *= x |
|
309 return z |
|
310 \end{verbatim} |
|
311 |
|
312 \section{Problem set 2} |
|
313 The focus is on writing functions and calling them. |
|
314 \begin{description} |
|
315 \item[2.1] Write a function to return the gcd of two numbers. |
|
316 \item[2.2 Primitive Pythagorean Triads] 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. \\ |
|
317 Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100 |
|
318 \item[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). |
|
319 \item[2.4 Aliquot] 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.\\ |
|
320 Write a function that returns the aliquot number of a given number. |
|
321 \item[2.5 Amicable pairs] A pair of numbers (a, b) is said to be \emph{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ |
|
322 Example: \texttt{220, 284}\\ |
|
323 Write a program that prints all five digit amicable pairs. |
|
324 \end{description} |
|
325 |
|
326 \section{Lists} |
|
327 \subsection{List creation and indexing} |
|
328 \begin{verbatim} |
|
329 >>> a = [] # An empty list. |
|
330 >>> a = [1, 2, 3, 4] # More useful. |
|
331 >>> len(a) |
|
332 4 |
|
333 >>> a[0] + a[1] + a[2] + a[-1] |
|
334 10 |
|
335 \end{verbatim} |
|
336 |
|
337 \begin{verbatim} |
|
338 >>> a[1:3] # A slice. |
|
339 [2, 3] |
|
340 >>> a[1:-1] |
|
341 [2, 3, 4] |
|
342 >>> a[1:] == a[1:-1] |
|
343 False |
|
344 \end{verbatim} |
|
345 Explain last result |
|
346 |
|
347 \newpage |
|
348 \subsection{List: more slices} |
|
349 \begin{verbatim} |
|
350 >>> a[0:-1:2] # Notice the step! |
|
351 [1, 3] |
|
352 >>> a[::2] |
|
353 [1, 3] |
|
354 >>> a[-1::-1] |
|
355 \end{verbatim} |
|
356 What do you think the last one will do?\\ |
|
357 \emph{Note: Strings also use same indexing and slicing.} |
|
358 \subsection{List: examples} |
|
359 \begin{verbatim} |
|
360 >>> a = [1, 2, 3, 4] |
|
361 >>> a[:2] |
|
362 [1, 3] |
|
363 >>> a[0:-1:2] |
|
364 [1, 3] |
|
365 \end{verbatim} |
|
366 \emph{Lists are mutable (unlike strings)} |
|
367 |
|
368 \begin{verbatim} |
|
369 >>> a[1] = 20 |
|
370 >>> a |
|
371 [1, 20, 3, 4] |
|
372 \end{verbatim} |
|
373 |
|
374 \subsection{Lists are mutable and heterogenous} |
|
375 \begin{verbatim} |
|
376 >>> a = ['spam', 'eggs', 100, 1234] |
|
377 >>> a[2] = a[2] + 23 |
|
378 >>> a |
|
379 ['spam', 'eggs', 123, 1234] |
|
380 >>> a[0:2] = [1, 12] # Replace items |
|
381 >>> a |
|
382 [1, 12, 123, 1234] |
|
383 >>> a[0:2] = [] # Remove items |
|
384 >>> a.append( 12345 ) |
|
385 >>> a |
|
386 [123, 1234, 12345] |
|
387 \end{verbatim} |
|
388 |
|
389 \subsection{List methods} |
|
390 \begin{verbatim} |
|
391 >>> a = ['spam', 'eggs', 1, 12] |
|
392 >>> a.reverse() # in situ |
|
393 >>> a |
|
394 [12, 1, 'eggs', 'spam'] |
|
395 >>> a.append(['x', 1]) |
|
396 >>> a |
|
397 [12, 1, 'eggs', 'spam', ['x', 1]] |
|
398 >>> a.extend([1,2]) # Extend the list. |
|
399 >>> a.remove( 'spam' ) |
|
400 >>> a |
|
401 [12, 1, 'eggs', ['x', 1], 1, 2] |
|
402 \end{verbatim} |
|
403 |
|
404 \subsection{List containership} |
|
405 \begin{verbatim} |
|
406 >>> a = ['cat', 'dog', 'rat', 'croc'] |
|
407 >>> 'dog' in a |
|
408 True |
|
409 >>> 'snake' in a |
|
410 False |
|
411 >>> 'snake' not in a |
|
412 True |
|
413 >>> 'ell' in 'hello world' |
|
414 True |
|
415 \end{verbatim} |
|
416 \subsection{Tuples: immutable} |
|
417 \begin{verbatim} |
|
418 >>> t = (0, 1, 2) |
|
419 >>> print t[0], t[1], t[2], t[-1] |
|
420 0 1 2 2 |
|
421 >>> t[0] = 1 |
|
422 Traceback (most recent call last): |
|
423 File "<stdin>", line 1, in ? |
|
424 TypeError: object does not support item assignment |
|
425 \end{verbatim} |
|
426 Multiple return values are actually a tuple.\\ |
|
427 Exchange is tuple (un)packing |
|
428 \subsection{\texttt{range()} function} |
|
429 \begin{verbatim} |
|
430 >>> range(7) |
|
431 [0, 1, 2, 3, 4, 5, 6] |
|
432 >>> range( 3, 9) |
|
433 [3, 4, 5, 6, 7, 8] |
|
434 >>> range( 4, 17, 3) |
|
435 [4, 7, 10, 13, 16] |
|
436 >>> range( 5, 1, -1) |
|
437 [5, 4, 3, 2] |
|
438 >>> range( 8, 12, -1) |
|
439 [] |
|
440 \end{verbatim} |
|
441 |
|
442 \subsection{\texttt{for\ldots range(\ldots)} idiom} |
|
443 \begin{verbatim} |
|
444 In [83]: for i in range(5): |
|
445 ....: print i, i * i |
|
446 ....: |
|
447 ....: |
|
448 0 0 |
|
449 1 1 |
|
450 2 4 |
|
451 3 9 |
|
452 4 16 |
|
453 \end{verbatim} |
|
454 |
|
455 \subsection{\texttt{for}: the list companion} |
|
456 |
|
457 \begin{verbatim} |
|
458 In [84]: a = ['a', 'b', 'c'] |
|
459 In [85]: for x in a: |
|
460 ....: print x, chr( ord(x) + 10 ) |
|
461 ....: |
|
462 a k |
|
463 b l |
|
464 c m |
|
465 \end{verbatim} |
|
466 |
|
467 \subsection{\texttt{for}: the list companion} |
|
468 \begin{verbatim} |
|
469 In [89]: for p, ch in enumerate( a ): |
|
470 ....: print p, ch |
|
471 ....: |
|
472 ....: |
|
473 0 a |
|
474 1 b |
|
475 2 c |
|
476 \end{verbatim} |
|
477 Try: \texttt{print enumerate(a)} |
|
478 |
|
479 \section{Problem set 3} |
|
480 As you can guess, idea is to use \texttt{for}! |
|
481 |
|
482 \begin{description} |
|
483 \item[3.1] Which of the earlier problems is simpler when we use \texttt{for} instead of \texttt{while}? |
|
484 \item[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. |
|
485 \item[3.3] Given two real numbers \texttt{a, b}, and an integer \texttt{N}, write a |
|
486 function named \texttt{linspace( a, b, N)} that returns an ordered list |
|
487 of \texttt{N} points starting with \texttt{a} and ending in \texttt{b} and |
|
488 equally spaced.\\ |
|
489 For example, \texttt{linspace(0, 5, 11)}, should return, \\ |
|
490 \begin{verbatim} |
|
491 [ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, |
|
492 3.0 , 3.5, 4.0 , 4.5, 5.0 ] |
|
493 \end{verbatim} |
|
494 \item[3.4a] Use the \texttt{linspace} function and generate a list of N tuples of the form\\ |
|
495 \texttt{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions, |
|
496 \begin{itemize} |
|
497 \item \texttt{f(x) = sin(x)} |
|
498 \item \texttt{f(x) = sin(x) + sin(10*x)}. |
|
499 \end{itemize} |
|
500 |
|
501 \item[3.4b] Using the tuples generated earlier, determine the intervals where the roots of the functions lie. |
|
502 \end{description} |
|
503 |
|
504 \section{IO} |
|
505 \subsection{Simple tokenizing and parsing} |
|
506 \begin{verbatim} |
|
507 s = """The quick brown fox jumped |
|
508 over the lazy dog""" |
|
509 for word in s.split(): |
|
510 print word.capitalize() |
|
511 \end{verbatim} |
|
512 |
|
513 \begin{description} |
|
514 \item[4.1] Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list\\ |
|
515 \texttt{[1,3,4,5,6,7,12,15,18,19,20,21]} |
|
516 \end{description} |
|
517 |
|
518 \subsection{File handling} |
|
519 \begin{verbatim} |
|
520 >>> f = open('/path/to/file_name') |
|
521 >>> data = f.read() # Read entire file. |
|
522 >>> line = f.readline() # Read one line. |
|
523 >>> f.close() # close the file. |
|
524 \end{verbatim} |
|
525 Writing files |
|
526 \begin{verbatim} |
|
527 >>> f = open('/path/to/file_name', 'w') |
|
528 >>> f.write('hello world\n') |
|
529 >>> f.close() |
|
530 \end{verbatim} |
|
531 |
|
532 \subsection{File and \texttt{for}} |
|
533 \begin{verbatim} |
|
534 >>> f = open('/path/to/file_name') |
|
535 >>> for line in f: |
|
536 ... print line |
|
537 ... |
|
538 \end{verbatim} |
|
539 |
|
540 \begin{description} |
|
541 \item[4.2] The given file has lakhs of records in the form: |
|
542 \texttt{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}. |
|
543 Some entries may be empty. Read the data from this file and print the |
|
544 name of the student with the maximum total marks. |
|
545 \item[4.3] For the same data file compute the average marks in different |
|
546 subjects, the student with the maximum mark in each subject and also |
|
547 the standard deviation of the marks. Do this efficiently. |
|
548 \end{description} |
|
549 |
|
550 \section{Modules} |
|
551 \begin{verbatim} |
|
552 >>> sqrt(2) |
|
553 Traceback (most recent call last): |
|
554 File "<stdin>", line 1, in <module> |
|
555 NameError: name 'sqrt' is not defined |
|
556 >>> import math |
|
557 >>> math.sqrt(2) |
|
558 1.4142135623730951 |
|
559 |
|
560 >>> from math import sqrt |
|
561 >>> from math import * |
|
562 >>> from os.path import exists |
|
563 \end{verbatim} |
|
564 |
|
565 \subsection{Modules: example} |
|
566 \begin{verbatim} |
|
567 # --- arith.py --- |
|
568 def gcd(a, b): |
|
569 if a%b == 0: return b |
|
570 return gcd(b, a%b) |
|
571 def lcm(a, b): |
|
572 return a*b/gcd(a, b) |
|
573 # ------------------ |
|
574 >>> import arith |
|
575 >>> arith.gcd(26, 65) |
|
576 13 |
|
577 >>> arith.lcm(26, 65) |
|
578 130 |
|
579 \end{verbatim} |
|
580 \section{Problem set 5} |
|
581 \begin{description} |
|
582 \item[5.1] Put all the functions you have written so far as part of the problems |
|
583 into one module called \texttt{iitb.py} and use this module from IPython. |
|
584 \end{description} |
|
585 \newpage |
|
586 |
|
587 \section{Data Structures} |
|
588 |
|
589 \subsection{Dictonary} |
|
590 \begin{verbatim} |
|
591 >>>d = { 'Hitchhiker\'s guide' : 42, 'Terminator' : 'I\'ll be back'} |
|
592 >>>d['Terminator'] |
|
593 "I'll be back" |
|
594 \end{verbatim} |
|
595 |
|
596 \subsection{Problem Set 6.1} |
|
597 \begin{description} |
|
598 \item[6.1.1] You are given date strings of the form ``29, Jul 2009'', or ``4 January 2008''. In other words a number a string and another number, with a comma sometimes separating the items.Write a function that takes such a string and returns a tuple (yyyy, mm, dd) where all three elements are ints. |
|
599 \item[6.1.2] Count word frequencies in a file. |
|
600 \item[6.1.3] Find the most used Python keywords in your Python code (import keyword). |
|
601 \end{description} |
|
602 \subsection{Set} |
|
603 \begin{verbatim} |
|
604 >>> f10 = set([1,2,3,5,8]) |
|
605 >>> p10 = set([2,3,5,7]) |
|
606 >>> f10|p10 |
|
607 set([1, 2, 3, 5, 7, 8]) |
|
608 >>> f10&p10 |
|
609 set([2, 3, 5]) |
|
610 >>> f10-p10 |
|
611 set([8, 1]) |
|
612 >>> p10-f10, f10^p10 |
|
613 set([7]), set([1, 7, 8]) |
|
614 >>> set([2,3]) < p10 |
|
615 True |
|
616 >>> set([2,3]) <= p10 |
|
617 True |
|
618 >>> 2 in p10 |
|
619 True |
|
620 >>> 4 in p10 |
|
621 False |
|
622 >>> len(f10) |
|
623 5 |
|
624 \end{verbatim} |
|
625 |
|
626 \subsection{Problem Set 6.2} |
|
627 \begin{description} |
|
628 \item[6.2.1] Given a dictionary of the names of students and their marks, identify how many duplicate marks are there? and what are these? |
|
629 \item[6.2.2] Given a string of the form ``4-7, 9, 12, 15'' find the numbers missing in this list for a given range. |
|
630 \end{description} |
|
631 \subsection{Fuctions: default arguments} |
|
632 \begin{verbatim} |
|
633 def ask_ok(prompt, complaint='Yes or no!'): |
|
634 while True: |
|
635 ok = raw_input(prompt) |
|
636 if ok in ('y', 'ye', 'yes'): |
|
637 return True |
|
638 if ok in ('n', 'no', 'nop', |
|
639 'nope'): |
|
640 return False |
|
641 print complaint |
|
642 |
|
643 ask_ok('?') |
|
644 ask_ok('?', '[Y/N]') |
|
645 \end{verbatim} |
|
646 \newpage |
|
647 \subsection{Fuctions: keyword arguments} |
|
648 \begin{verbatim} |
|
649 def ask_ok(prompt, complaint='Yes or no!'): |
|
650 while True: |
|
651 ok = raw_input(prompt) |
|
652 if ok in ('y', 'ye', 'yes'): |
|
653 return True |
|
654 if ok in ('n', 'no', 'nop', |
|
655 'nope'): |
|
656 return False |
|
657 print complaint |
|
658 |
|
659 ask_ok(prompt='?') |
|
660 ask_ok(prompt='?', complaint='[y/n]') |
|
661 ask_ok(complaint='[y/n]', prompt='?') |
|
662 \end{verbatim} |
|
663 \subsection{List Comprehensions} |
|
664 Lets say we want to squares of all the numbers from 1 to 100 |
|
665 \begin{verbatim} |
|
666 squares = [] |
|
667 for i in range(1, 100): |
|
668 squares.append(i * i) |
|
669 # list comprehension |
|
670 squares = [i*i for i in range(1, 100) |
|
671 if i % 10 in [1, 2, 5, 7]] |
|
672 \end{verbatim} |
|
673 \end{document} |