Basic Python

Basic Python

  1. Simple arithmetics (5 min). Calculate:

    1. $2^5$

      >>> 2**5
      32
      
    2. 31/2

      >>> 31/2 #integer division (Python < 2.6)
      15
      >>> 31/2.
      15.5
      
    3. 015 + 32

      >>> 015 + 32 # numbers prefixed with 0 are in octal system
      45
      
    4. 11 mod 2

      >>> 11 % 2
      1
      

    Are they results like you expected?

  2. Lists (30 min). Define following lists:

    1. Odd numbers from 1 to 11. Hint: Use range method.

      >>> x = range(1,12,2)
      >>> print x
      [1, 3, 5, 7, 9, 11]
      
    2. A list of arbitrary number of zeros

      >>> a = [0]*10
      >>> print a
      [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
      
    3. Sequence of letters from "a" to "k". Hint: use chr method.

      >>> letters = [chr(c) for c in xrange(97,108, 1)]
      >>> print letters
      ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
      
    4. Elements of power series ($A_i = \sum_{k=1}^{i} x^i$, x = 1.2) smaller than a 10.

      >>> x_0 = 1.2
      >>> power = [x_0]
      >>> max_a = 10.
      >>> x = x_0
      >>> while power[-1] < max_a:
      ...     x*=x_0
      ...     power.append(power[-1]+x)
      >>> print power[:-1]
      [1.2, 2.6399999999999997, 4.3679999999999994, 6.4415999999999993, 8.9299199999999992]
      
    5. 10x10 identity matrix.

      >>> import pprint
      >>> matrix2 =  [[int(i==j) for i in range(10)] for j in range(10)]
      >>> pprint.pprint(matrix2)
      [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]]
      
  3. Introspection (20 min). In Python interpreter define following variables:

    1. empty string

      >>> def list_methods(x):
      ...     for method in dir(x):
      ...         if not method.startswith('__'):
      ...             docstring = getattr(x, method).__doc__
      ...             print method, ": ", docstring.splitlines()[0]
      
      >>> list_methods("")
      capitalize :  S.capitalize() -> string
      center :  S.center(width[, fillchar]) -> string
      count :  S.count(sub[, start[, end]]) -> int
      decode :  S.decode([encoding[,errors]]) -> object
      encode :  S.encode([encoding[,errors]]) -> object
      endswith :  S.endswith(suffix[, start[, end]]) -> bool
      expandtabs :  S.expandtabs([tabsize]) -> string
      find :  S.find(sub [,start [,end]]) -> int
      index :  S.index(sub [,start [,end]]) -> int
      isalnum :  S.isalnum() -> bool
      isalpha :  S.isalpha() -> bool
      isdigit :  S.isdigit() -> bool
      islower :  S.islower() -> bool
      isspace :  S.isspace() -> bool
      istitle :  S.istitle() -> bool
      isupper :  S.isupper() -> bool
      join :  S.join(sequence) -> string
      ljust :  S.ljust(width[, fillchar]) -> string
      lower :  S.lower() -> string
      lstrip :  S.lstrip([chars]) -> string or unicode
      replace :  S.replace (old, new[, count]) -> string
      rfind :  S.rfind(sub [,start [,end]]) -> int
      rindex :  S.rindex(sub [,start [,end]]) -> int
      rjust :  S.rjust(width[, fillchar]) -> string
      rsplit :  S.rsplit([sep [,maxsplit]]) -> list of strings
      rstrip :  S.rstrip([chars]) -> string or unicode
      split :  S.split([sep [,maxsplit]]) -> list of strings
      splitlines :  S.splitlines([keepends]) -> list of strings
      startswith :  S.startswith(prefix[, start[, end]]) -> bool
      strip :  S.strip([chars]) -> string or unicode
      swapcase :  S.swapcase() -> string
      title :  S.title() -> string
      translate :  S.translate(table [,deletechars]) -> string
      upper :  S.upper() -> string
      zfill :  S.zfill(width) -> string
      
    2. empty list

      >>> list_methods([])
      append :  L.append(object) -- append object to end
      count :  L.count(value) -> integer -- return number of occurrences of value
      extend :  L.extend(iterable) -- extend list by appending elements from the iterable
      index :  L.index(value, [start, [stop]]) -> integer -- return first index of value
      insert :  L.insert(index, object) -- insert object before index
      pop :  L.pop([index]) -> item -- remove and return item at index (default last)
      remove :  L.remove(value) -- remove first occurrence of value
      reverse :  L.reverse() -- reverse *IN PLACE*
      sort :  L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
      
    3. empty dictionary

      >>> list_methods({})
      clear :  D.clear() -> None.  Remove all items from D.
      copy :  D.copy() -> a shallow copy of D
      fromkeys :  dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
      get :  D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
      has_key :  D.has_key(k) -> True if D has a key k, else False
      items :  D.items() -> list of D's (key, value) pairs, as 2-tuples
      iteritems :  D.iteritems() -> an iterator over the (key, value) items of D
      iterkeys :  D.iterkeys() -> an iterator over the keys of D
      itervalues :  D.itervalues() -> an iterator over the values of D
      keys :  D.keys() -> list of D's keys
      pop :  D.pop(k[,d]) -> v, remove specified key and return the corresponding value
      popitem :  D.popitem() -> (k, v), remove and return some (key, value) pair as a
      setdefault :  D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
      update :  D.update(E, **F) -> None.  Update D from E and F: for k in E: D[k] = E[k]
      values :  D.values() -> list of D's values
      

    Using built-in dir and help method find out which methods these data structures offer. Print a table with non-special methods (without underscores) and first line of their docstring. Give a working example documenting at least one of the listed methods.

  4. Enigma (20 min). Recover the message hidden in the string using the following translation: a ➔ c, b ➔ d, ..., z ➔ b.

    g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr
    amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q
    ufw rfgq rcvr gq qm jmle. sqgle qrp.rpylqjyrc() gq pcamkkclbcb!
    
    >>> text = """g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr
    ... amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q
    ... ufw rfgq rcvr gq qm jmle. sqgle qrp.rpylqjyrc() gq pcamkkclbcb!"""
    >>> trans_tab = range(256)
    >>> trans_tab[97:123] = range(99,123) + [97,98]
    >>> print text.translate("".join(map(chr,trans_tab)))
    i hope you didnt translate it by hand. thats what
    computers are for. doing it in by hand is inefficient and that's
    why this text is so long. using str.translate() is recommended!
    
  5. Binary conversion (20 min). Write a program converting integers to their binary representation. You can store the result either in a list or in a string.

    >>> def dec2bin(x):
    ...    binary = []
    ...    while x>0:
    ...        binary.append(x % 2)
    ...        x = x/2
    ...    return binary
    >>> dec2bin(9)
    [1, 0, 0, 1]
    
  6. Cashier (45 min). Implement a simple cashier machine with the following features :

    1. "codebar" associated with each product,
    2. reading of a price list from a file Hint: you will need to wait until the second part of the lecture or skip to the relevant section of the handouts,
    3. an interactive entry of a codebar or a product name. Hint: use raw_input
    4. warning if the product doesn't exist
    5. printing of subtotals after entering each product
    6. printing of the final bill
    7. your ideas
  7. Import. Write a program that counts lines and characters in a file. With your editor, code a Python module called mymode.py which provides three functions:

    • countlines(name) - reads an input file and count the number of lines in it Hint: file.readlines() does most of the work for you.
    • countChars(name) - reads an input file and counts the number of characters in it Hint: file.read() returns a single string.
    • test(name) - calls both counting functions with a given input filename.
    """
    Functions counting the number of lines and characters in a file
    """
    import sys
    
    def countlines(name):
        """Returns number of lines in a file 'name'"""
        f = open(name, 'r')
        return len(f.readlines())
    
    def countChars(name):
        """Return number of characters in a file 'name'"""
        f = open(name, 'r')
        return len(f.read())
    
    def test(name):
        """Prints number of lines and characters in a file"""
        print "File:", name
        print "Number of lines:", countlines(name)
        print "Number of characters:", countChars(name)
    
    if __name__ == '__main__':
        #you can pass the filenames as command line arguments
        # command line arguments are available in a list defined in
        # sys module (sys.argv)
        if sys.argv[1:]:
            for name in sys.argv[1:]:
                test(name)
        else:
            print "Usage: python mymode.py filename(s)"
    

    Next, test your module interactively, using import. What if your module is in a different directory than your current working directory? Add a "main" function to your module.

    >>> import mymode
    >>> mymode.test("mymode.py")
    File: mymode.py
    Number of lines: 32
    Number of characters: 858
    
  8. Geometry. In a module geometry create a Point class that consists of an ordered pair (x,y) representing a point's location on the X and Y axes. X and Y coordinates are passed to the constructor on instatiation and default to origin for any missing coordinate.

    from math import sqrt
    
    class Point(object):
    
        def __init__(self, x=0, y=0):
            self.x = x
            self.y = y
    
        def __str__(self):
            return "point (%.1f, %.1f)" % (self.x, self.y)
    
        def distance(self, point2):
            """returns Euclidean distance from point point2"""
            return sqrt((self.x - point2.x)**2 + (self.y - point2.y)**2)
    
    >>> from geometry import Point
    >>> point0 = Point()
    >>> point1 = Point(2,3)
    >>> print  "distance %s->%s = %f" % (point0, point1,  point1.distance(point0))
    distance point (0.0, 0.0)->point (2.0, 3.0) = 3.605551
    
  9. Ecosystem (1h). Program an ecosystem in which each organism belongs to a hierarchical tree (for example, dog is a mamal, mamal is an animal, an animal is a living organism). Implement following functions and attributes:

    1. name of the species and its systematic classification,
    2. position in the environment,
    3. their specific means of locomotion,
    4. reproduction and death.

    In each iteration each organism should update its state (move, reproduce or die). You can also provide a simple ASCII output showing the position of the organisms.

    As a starting point you can take the program ecosystem.py

 
solutions.txt · Last modified: 2009/09/02 18:54 by bartosz
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki