Beruflich Dokumente
Kultur Dokumente
Todays class
Getting your feet wet with Python programming. (Review of yesterdays stuff.)
These slides are available for download from: http://www.gc3.uzh.ch/teaching/lsci2011/lab07.pdf
Python II
R. Murri,
Yesterdays homework
Write a function sp(C,L ) that returns a pair (tuple) of elements from a list L whose sum is integer C. (Unspecied: what should it do when no pairs of values from L sums to C?)
Python II
R. Murri,
Testing solutions
Rather than inspecting each solutions code, we shall write a test class, using Python standard library unit testing facility. Your solution is correct if it passes the test.
Python II
R. Murri,
Pythons unittest requires one to dene a subclass of unittest.TestCase. All methods whose name starts with test are executed; if none errors out, the test is passed. Test methods should use methods assertEqual, assertTrue, etc. dened by class TestCase to check if test conditions are satised.
Reference: http://docs.python.org/library/unittest.html
Python II
R. Murri,
This syntax allows you to import a module but assign it a different name.
def test_sp_1(self): (x, y) = sp(100, [5, 75, 25]) self.assertEqual((x,y), (75, 25)) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertTrue((x,y) == (4,4)) if __name__ == "__main__": ut.main()
Python II
R. Murri,
def test_sp_1(self): (x, y) = sp(100, [5, 75, 25]) self.assertEqual((x,y), (75, 25)) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertTrue((x,y) == (4,4)) if __name__ == "__main__": ut.main()
Python II
R. Murri,
A method declaration looks exactly like a function denition. Every method must have at least one argument, named self.
More on self
def test_sp_1( self ): (x, y) = sp(100, [5, 75, 25]) self.assertEqual((x,y), (75, 25)) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertTrue((x,y) == (4,4)) if __name__ == "__main__": ut.main()
Python II
R. Murri,
self is a reference to the object instance (like, e.g., import unittest as ut this in Java). It is used to access attributes and class SpTest(ut.TestCase): invoke methods of the def test_sp_1(self): object itself.
(x, y) = sp(100, [5, 75, 25]) self .assertEqual((x,y), (75, 25)) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertTrue((x,y) == (4,4)) if __name__ == "__main__": ut.main()
More on self
Python II
R. Murri,
def test_sp_1(self): (x, y) = sp(100, [5, 75, 25]) self.assertEqual((x,y), (75, 25)) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertTrue((x,y) == (4,4)) if __name__ == "__main__": ut.main()
Python II
R. Murri,
Python idiom: execute ut.main() iff this le is the main script, i.e., it is not being read as a module.
def test_sp_1(self): (x, y) = sp(100, [5, 75, 25]) self.assertEqual((x,y), (75, 25)) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertTrue((x,y) == (4,4)) if name == " main ": ut.main()
Python II
R. Murri,
Time to check!
0. Download the test code from http: //www.gc3.uzh.ch/teaching/lsci2011/lab06/sptest.py 1. Add your sp function to it. 2. Run the script: python sptest.py --verbose 3. If you get the following output: congratulations! your sp implementation works as expected. test_sp_1 (__main__.SpTest) ... ok test_sp_2 (__main__.SpTest) ... ok ------------------------------------------Ran 2 tests in 0.000s OK
Python II R. Murri, Large Scale Computing Infrastructures, Nov. 10, 2011
File I/O
open(path,mode) Return a Python file object for reading or writing the le located at path. Mode is one of r, w or a for reading, writing (truncates on open), appending. You can add a + character to enable read+write (other effects being the same). close() Close an open le. for line in file obj Loop over lines in the le one by one.
Reference: http://docs.python.org/library/stdtypes.html#le-objects
Python II R. Murri, Large Scale Computing Infrastructures, Nov. 10, 2011
Exercise 1
1. Implement a function count_lines(stream), that returns the number of lines in stream (a le-like object). 2. Implement a function keys_for_value(D, val), which returns the list of keys that are associated to value val in dictionary D.
Python II
R. Murri,
The in operator
Evaluates to True if x is equal to a value contained in the S sequence (list, tuple, set).
x in D
Python II
R. Murri,
The read(n) method can be used to read at most n bytes from a le-like object:
>>> s = stream.read(2) >>> s == py True
Exercise 2
Implement a function count_chars(stream), that returns a dictionary, mapping each character into the count of its occurrences in stream. Characters that do not occur in the input should not be present in the returned dictionary. You can assume stream is formed of ASCII characters. 1. Write test cases for the function, before writing it. At the very least, check: That count_chars() on an empty stream returns an empty dictionary; That count_chars() on a stream whose content is the string aaaaaa returns the dictionary {a:6} That count_chars() on a stream whose content is the string ababab returns the dictionary {a:3, b:3} 2. Verify that the test cases fail. 3. Write the function, and check that all tests pass.
Python II R. Murri, Large Scale Computing Infrastructures, Nov. 10, 2011
Operations on strings
Assume s is a Python str object.
s.capitalize(), s.lower(), s.upper()
Return a copy of the string capitalized / turned all lowercase / turned all uppercase.
s.split(t)
Split s at every occurrence of t and return list of parts. If t is omitted, split on whitespace.
s.startswith(t), s.endswith(t)
Python II
R. Murri,
Exercise 3
Implement a function count_words, that counts the number of distinct words occurring in stream. Words are delimited by whitespace; case does not matter.
Python II
R. Murri,
Filesystem operations
These functions are available from the os module. os.getcwd(), os.chdir(path) Return the path to the current working directory / Change the current working directory to path. os.listdir(dir) Return list of entries in directory dir (omitting . and ..) os.mkdir(path) Create a directory; fails if the directory already exists. Assumes that all parent directories exist already. os.makedirs(path) Create a directory; no-op if the directory already exists. Creates all the intermediate-level directories needed to contain the leaf. Reference: http://docs.python.org/library/os.html
Python II R. Murri, Large Scale Computing Infrastructures, Nov. 10, 2011
Filesystem operations, II
These functions are available from the os.path module.
os.path.exists(path), os.path.isdir(path)
Return the base name (the part after the last / character) or the directory name (the part before the last / character).
os.path.abspath(path)
Exercise 4
Write a Python program rename.py with the following command-line:
python rename.py EXT1 EXT2 DIR [DIR ...]
where: ext1,ext2 Are le name extensions (without the leading dot), e.g., jpg and jpeg. dir Is directory path; possibly, many directories names can be given on the command-line. The rename.py command should rename all les in directory DIR, that end with extension ext1 to end with extension ext2 instead.
Python II
R. Murri,
More exercises...
(In case you want to practice.) Basic Python Exercises from Googles Python class: http://code.google.com/edu/languages/ google-python-class/exercises/basic.html The Python Challenge: http://www.pythonchallenge.com/ Python Koans: https://github.com/gregmalcolm/python koans
Python II
R. Murri,
The self variable is a reference to the object itself. You need to use self when accessing other methods or attributes of the object.
Back to Unit Testing
Python II R. Murri, Large Scale Computing Infrastructures, Nov. 10, 2011
Any name that is not in one of the above scopes must be qualied. So you have to write self.assertEqual to call a method on this object, ut.TestCase to mean a class dened in module ut, etc.
Python II R. Murri, Large Scale Computing Infrastructures, Nov. 10, 2011