day1/Problems.tex
changeset 0 9243d75024cc
equal deleted inserted replaced
-1:000000000000 0:9243d75024cc
       
     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 Kaprekar's constant]
       
   241   \begin{enumerate}
       
   242     \item Take a four digit number--with at least two digits different.
       
   243     \item Arrange the digits in ascending and descending order, giving A and D respectively.
       
   244     \item Leave leading zeros in A!
       
   245     \item Subtract A from D.
       
   246     \item With the result, repeat from step 2.
       
   247   \end{enumerate}
       
   248   Write a program to accept a 4-digit number and display the progression to Kaprekar's constant.
       
   249 
       
   250 \item[1.4]
       
   251   Write a program that prints the following pyramid on the screen. 
       
   252   \begin{verbatim}
       
   253 1
       
   254 2  2
       
   255 3  3  3
       
   256 4  4  4  4
       
   257   \end{verbatim}
       
   258 The number of lines must be obtained from the user as input.\\
       
   259 When can your code fail?
       
   260 \end{description}
       
   261 
       
   262 \subsection{Functions: examples}
       
   263   \begin{verbatim}
       
   264 def signum( r ):
       
   265     """returns 0 if r is zero
       
   266     -1 if r is negative
       
   267     +1 if r is positive"""
       
   268     if r < 0:
       
   269         return -1
       
   270     elif r > 0:
       
   271         return 1
       
   272     else:
       
   273         return 0
       
   274 
       
   275 def pad( n, size ): 
       
   276     """pads integer n with spaces
       
   277     into a string of length size
       
   278     """
       
   279     SPACE = ' '
       
   280     s = str( n )
       
   281     padSize = size - len( s )
       
   282     return padSize * SPACE + s
       
   283   \end{verbatim}
       
   284 What about \%3d?
       
   285 
       
   286 \subsection  {What does this function do?}
       
   287   \begin{verbatim}
       
   288 def what( n ):
       
   289     if n < 0: n = -n
       
   290     while n > 0:
       
   291         if n % 2 == 1:
       
   292             return False
       
   293         n /= 10
       
   294     return True
       
   295   \end{verbatim}
       
   296 \newpage
       
   297 
       
   298 \subsection{What does this function do?}
       
   299 \begin{verbatim}
       
   300 def what( n ):
       
   301     i = 1    
       
   302     while i * i < n:
       
   303         i += 1
       
   304     return i * i == n, i
       
   305   \end{verbatim}
       
   306 
       
   307 \subsection{What does this function do?}
       
   308   \begin{verbatim}
       
   309 def what( n, x ):
       
   310     z = 1.0
       
   311     if n < 0:
       
   312         x = 1.0 / x
       
   313         n = -n
       
   314     while n > 0:
       
   315         if n % 2 == 1:
       
   316             z *= x
       
   317         n /= 2
       
   318         x *= x
       
   319     return z
       
   320   \end{verbatim}
       
   321 
       
   322 \section{Problem set 2}
       
   323   The focus is on writing functions and calling them.
       
   324 \begin{description}
       
   325   \item[2.1] Write a function to return the gcd of two numbers.
       
   326   \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. \\
       
   327 Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100
       
   328 \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).
       
   329 \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.\\
       
   330   Write a function that returns the aliquot number of a given number. 
       
   331 \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.\\
       
   332   Example: \texttt{220, 284}\\
       
   333   Write a program that prints all five digit amicable pairs.
       
   334 \end{description}
       
   335 
       
   336 \section{Lists}
       
   337 \subsection{List creation and indexing}
       
   338 \begin{verbatim}
       
   339 >>> a = [] # An empty list.
       
   340 >>> a = [1, 2, 3, 4] # More useful.
       
   341 >>> len(a) 
       
   342 4
       
   343 >>> a[0] + a[1] + a[2] + a[-1]
       
   344 10
       
   345 \end{verbatim}
       
   346 
       
   347 \begin{verbatim}
       
   348 >>> a[1:3] # A slice.
       
   349 [2, 3]
       
   350 >>> a[1:-1]
       
   351 [2, 3, 4]
       
   352 >>> a[1:] == a[1:-1]
       
   353 False  
       
   354 \end{verbatim}
       
   355 Explain last result
       
   356 
       
   357 \newpage
       
   358 \subsection{List: more slices}
       
   359 \begin{verbatim}
       
   360 >>> a[0:-1:2] # Notice the step!
       
   361 [1, 3]
       
   362 >>> a[::2]
       
   363 [1, 3]
       
   364 >>> a[-1::-1]
       
   365 \end{verbatim}
       
   366 What do you think the last one will do?\\
       
   367 \emph{Note: Strings also use same indexing and slicing.}
       
   368   \subsection{List: examples}
       
   369 \begin{verbatim}
       
   370 >>> a = [1, 2, 3, 4]
       
   371 >>> a[:2]
       
   372 [1, 3]
       
   373 >>> a[0:-1:2]
       
   374 [1, 3]
       
   375 \end{verbatim}
       
   376 \emph{Lists are mutable (unlike strings)}
       
   377 
       
   378 \begin{verbatim}
       
   379 >>> a[1] = 20
       
   380 >>> a
       
   381 [1, 20, 3, 4]
       
   382 \end{verbatim}
       
   383 
       
   384   \subsection{Lists are mutable and heterogenous}
       
   385 \begin{verbatim}
       
   386 >>> a = ['spam', 'eggs', 100, 1234]
       
   387 >>> a[2] = a[2] + 23
       
   388 >>> a
       
   389 ['spam', 'eggs', 123, 1234]
       
   390 >>> a[0:2] = [1, 12] # Replace items
       
   391 >>> a
       
   392 [1, 12, 123, 1234]
       
   393 >>> a[0:2] = [] # Remove items
       
   394 >>> a.append( 12345 )
       
   395 >>> a
       
   396 [123, 1234, 12345]
       
   397 \end{verbatim}
       
   398 
       
   399   \subsection{List methods}
       
   400 \begin{verbatim}
       
   401 >>> a = ['spam', 'eggs', 1, 12]
       
   402 >>> a.reverse() # in situ
       
   403 >>> a
       
   404 [12, 1, 'eggs', 'spam']
       
   405 >>> a.append(['x', 1]) 
       
   406 >>> a
       
   407 [12, 1, 'eggs', 'spam', ['x', 1]]
       
   408 >>> a.extend([1,2]) # Extend the list.
       
   409 >>> a.remove( 'spam' )
       
   410 >>> a
       
   411 [12, 1, 'eggs', ['x', 1], 1, 2]
       
   412 \end{verbatim}
       
   413 
       
   414   \subsection{List containership}
       
   415   \begin{verbatim}
       
   416 >>> a = ['cat', 'dog', 'rat', 'croc']
       
   417 >>> 'dog' in a
       
   418 True
       
   419 >>> 'snake' in a
       
   420 False
       
   421 >>> 'snake' not in a
       
   422 True
       
   423 >>> 'ell' in 'hello world'
       
   424 True
       
   425   \end{verbatim}
       
   426   \subsection{Tuples: immutable}
       
   427 \begin{verbatim}
       
   428 >>> t = (0, 1, 2)
       
   429 >>> print t[0], t[1], t[2], t[-1] 
       
   430 0 1 2 2
       
   431 >>> t[0] = 1
       
   432 Traceback (most recent call last):
       
   433   File "<stdin>", line 1, in ?
       
   434 TypeError: object does not support item assignment
       
   435 \end{verbatim}  
       
   436     Multiple return values are actually a tuple.\\
       
   437     Exchange is tuple (un)packing
       
   438   \subsection{\texttt{range()} function}
       
   439   \begin{verbatim}
       
   440 >>> range(7)
       
   441 [0, 1, 2, 3, 4, 5, 6]
       
   442 >>> range( 3, 9)
       
   443 [3, 4, 5, 6, 7, 8]
       
   444 >>> range( 4, 17, 3)
       
   445 [4, 7, 10, 13, 16]
       
   446 >>> range( 5, 1, -1)
       
   447 [5, 4, 3, 2]
       
   448 >>> range( 8, 12, -1)
       
   449 []
       
   450   \end{verbatim}
       
   451 
       
   452   \subsection{\texttt{for\ldots range(\ldots)} idiom}
       
   453   \begin{verbatim}
       
   454 In [83]: for i in range(5):
       
   455    ....:     print i, i * i
       
   456    ....:     
       
   457    ....:     
       
   458 0 0
       
   459 1 1
       
   460 2 4
       
   461 3 9
       
   462 4 16
       
   463 \end{verbatim}
       
   464 
       
   465   \subsection{\texttt{for}: the list companion}
       
   466   
       
   467   \begin{verbatim}
       
   468 In [84]: a = ['a', 'b', 'c']
       
   469 In [85]: for x in a:
       
   470    ....:    print x, chr( ord(x) + 10 )
       
   471    ....:
       
   472 a  k
       
   473 b  l
       
   474 c  m
       
   475   \end{verbatim}
       
   476 
       
   477   \subsection{\texttt{for}: the list companion}
       
   478   \begin{verbatim}
       
   479 In [89]: for p, ch in enumerate( a ):
       
   480    ....:     print p, ch
       
   481    ....:     
       
   482    ....:     
       
   483 0 a
       
   484 1 b
       
   485 2 c
       
   486   \end{verbatim}
       
   487 Try: \texttt{print enumerate(a)}
       
   488 
       
   489 \section{Problem set 3}
       
   490   As you can guess, idea is to use \texttt{for}!
       
   491 
       
   492 \begin{description}
       
   493   \item[3.1] Which of the earlier problems is simpler when we use \texttt{for} instead of \texttt{while}? 
       
   494   \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.
       
   495   \item[3.3] Given two real numbers \texttt{a, b}, and an integer \texttt{N}, write a
       
   496   function named \texttt{linspace( a, b, N)} that returns an ordered list
       
   497   of \texttt{N} points starting with \texttt{a} and ending in \texttt{b} and
       
   498   equally spaced.\\
       
   499   For example, \texttt{linspace(0, 5, 11)}, should return, \\
       
   500 \begin{verbatim}
       
   501 [ 0.0 ,  0.5,  1.0 ,  1.5,  2.0 ,  2.5,  
       
   502   3.0 ,  3.5,  4.0 ,  4.5,  5.0 ]
       
   503 \end{verbatim}
       
   504   \item[3.4a] Use the \texttt{linspace} function and generate a list of N tuples of the form\\
       
   505 \texttt{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions,
       
   506 \begin{itemize}
       
   507   \item \texttt{f(x) = sin(x)}
       
   508   \item \texttt{f(x) = sin(x) + sin(10*x)}.
       
   509 \end{itemize}
       
   510 
       
   511 \item[3.4b] Using the tuples generated earlier, determine the intervals where the roots of the functions lie.
       
   512 \end{description}
       
   513 
       
   514 \section{IO}
       
   515   \subsection{Simple tokenizing and parsing}
       
   516   \begin{verbatim}
       
   517 s = """The quick brown fox jumped
       
   518        over the lazy dog"""
       
   519 for word in s.split():
       
   520     print word.capitalize()
       
   521   \end{verbatim}
       
   522 
       
   523   \begin{description}
       
   524     \item[4.1] Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \texttt{[1,3,4,5,6,7,12,15,18,19,20,21]}
       
   525 \end{description}
       
   526 
       
   527   \subsection{File handling}
       
   528 \begin{verbatim}
       
   529 >>> f = open('/path/to/file_name')
       
   530 >>> data = f.read() # Read entire file.
       
   531 >>> line = f.readline() # Read one line.
       
   532 >>> f.close() # close the file.
       
   533 \end{verbatim}
       
   534 Writing files
       
   535 \begin{verbatim}
       
   536 >>> f = open('/path/to/file_name', 'w')
       
   537 >>> f.write('hello world\n')
       
   538 >>> f.close()
       
   539 \end{verbatim}
       
   540 
       
   541     \subsection{File and \texttt{for}}
       
   542 \begin{verbatim}
       
   543 >>> f = open('/path/to/file_name')
       
   544 >>> for line in f:
       
   545 ...     print line
       
   546 ...
       
   547 \end{verbatim}
       
   548 
       
   549   \begin{description}
       
   550     \item[4.2] The given file has lakhs of records in the form:
       
   551     \texttt{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}.
       
   552     Some entries may be empty.  Read the data from this file and print the
       
   553     name of the student with the maximum total marks.
       
   554   \item[4.3] For the same data file compute the average marks in different
       
   555     subjects, the student with the maximum mark in each subject and also
       
   556     the standard deviation of the marks.  Do this efficiently.
       
   557 \end{description}
       
   558 
       
   559 \section{Modules}
       
   560 \begin{verbatim}
       
   561 >>> sqrt(2)
       
   562 Traceback (most recent call last):
       
   563   File "<stdin>", line 1, in <module>
       
   564 NameError: name 'sqrt' is not defined
       
   565 >>> import math        
       
   566 >>> math.sqrt(2)
       
   567 1.4142135623730951
       
   568 
       
   569 >>> from math import sqrt
       
   570 >>> from math import *
       
   571 >>> from os.path import exists
       
   572 \end{verbatim}
       
   573 
       
   574   \subsection{Modules: example}
       
   575   \begin{verbatim}
       
   576 # --- arith.py ---
       
   577 def gcd(a, b):
       
   578     if a%b == 0: return b
       
   579     return gcd(b, a%b)
       
   580 def lcm(a, b):
       
   581     return a*b/gcd(a, b)
       
   582 # ------------------
       
   583 >>> import arith
       
   584 >>> arith.gcd(26, 65)
       
   585 13
       
   586 >>> arith.lcm(26, 65)
       
   587 130
       
   588   \end{verbatim}
       
   589 
       
   590   \begin{description}
       
   591     \item[5.1] Put all the functions you have written so far as part of the problems
       
   592   into one module called \texttt{iitb.py} and use this module from IPython.
       
   593 \end{description}
       
   594 \end{document}