Python programming exercises, I

[Pages:25]Grid Computing Competence Center

Python programming exercises, I

Riccardo Murri Grid Computing Competence Center, Organisch-Chemisches Institut, University of Zurich

Nov. 10, 2011

Today's class

Getting your feet wet with Python programming. (Review of yesterday's stuff.) These slides are available for download from:

Python II

R. Murri, Large Scale Computing Infrastructures, Nov. 10, 2011

Yesterday's homework

Write a function sp(C,L) that returns a pair (tuple) of elements from a list L whose sum is integer C. (Unspecified: what should it do when no pairs of values from L sums to C?)

Python II

R. Murri, Large Scale Computing Infrastructures, Nov. 10, 2011

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, Large Scale Computing Infrastructures, Nov. 10, 2011

Python's unittest module

Python's unittest requires one to define 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. defined by class TestCase to check if test conditions are satisfied. Reference:

Python II

R. Murri, Large Scale Computing Infrastructures, Nov. 10, 2011

import unittest as ut class SpTest(ut.TestCase):

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, Large Scale Computing Infrastructures, Nov. 10, 2011

import unittest as ut class SpTest(ut.TestCase):

Declare a new class, ihneriting from the ut.TestCase class.

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, Large Scale Computing Infrastructures, Nov. 10, 2011

A method declaration looks

import unittest as ut

exactly like a function definition. Every method

class SpTest(ut.TestCase):

must have at least one argument, named self.

def test_sp_1( self ):

More on 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, Large Scale Computing Infrastructures, Nov. 10, 2011

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download