In [42]:
import unittest
def squares(n):
if n < 1:
raise ValueError
sq_list = [i**2 for i in range(1,n+1)]
print n, '-->', sq_list
return sq_list
class SquaresTest(unittest.TestCase):
def test_neg(self):
self.failUnlessRaises(ValueError, squares, -4)
def test_zero(self):
self.failUnlessRaises(ValueError, squares, 0)
def test_one(self):
self.failUnless([1] == squares(1))
def test_two(self):
self.failUnless([1,4] == squares(2))
def test_ten(self):
self.failUnless([1,4, 9, 16, 25, 36, 49, 64, 81, 100] == squares(10))
def test_eleven(self):
self.failUnlessEqual([1,4, 9, 16, 25, 36, 49, 64, 81, 100, 121], squares(11))
squares_suite = unittest.TestLoader().loadTestsFromTestCase(SquaresTest)
unittest.TextTestRunner().run(squares_suite)
Out[42]:
In [43]:
import unittest
def sum_squares(n):
sum = 0
for square in squares(n):
sum += square
print n,'--> sum: %s' % sum
return sum
class SumSquaresTest(unittest.TestCase):
def test_ss_one(self):
self.failUnlessEqual(1, sum_squares(1))
def test_ss_two(self):
self.failUnlessEqual(5, sum_squares(2))
def test_ss_ten(self):
self.failUnlessEqual(385, sum_squares(10))
def test_ss_eleven(self):
self.failUnlessEqual(506, sum_squares(11))
ss_suite = unittest.TestLoader().loadTestsFromTestCase(SumSquaresTest)
unittest.TextTestRunner().run(ss_suite)
Out[43]:
In [48]:
calls = 0
def fib(x, i):
'''
Recursively determine the xth fibonacci number.
i is used only for the indentation which represents the recursive
depth.
'''
global calls
calls += 1
i += 1
if x in [0,1]:
print "."*4*i, '%d --> %d' % (x, x)
return x
f1 = fib(x-1, i)
f2 = fib(x-2, i)
print "."*4*i, '%d --> %d' % (x, f1+f2)
return f1 + f2
answer = fib(8,0)
print 'Answer:', answer
print 'Calls :', calls