import unittest # Import the Python unit testingframeworkimport maths # Our code to test class MathsTest(unittest.TestCase): '''
Question:
import unittest # Import the Python unit testingframeworkimport maths # Our code to test
class MathsTest(unittest.TestCase): ''' Unit tests for our maths functions. '''
def test_add(self): ''' Tests the add function.''' self.assertEqual(maths.add(4,3),7) self.assertEqual(maths.add(0,3),3) self.assertEqual(maths.add(-4,3),-1) self.assertEqual(maths.add(-4,-4),-8)
def test_fibonacci(self): ''' Tests the fibonaccifunction. ''' self.assertEqual(maths.fibonacci(5), 5)
# This allows running the unit tests from the command line(python test_maths.py)if __name__ == '__main__': unittest.main()
def add(first, second): return first + second
def fibonacci(length): def internal(first, second, count): third = add(first, second) count -= 1 if count == 0: return third else: return internal(second,third, count)
return internal(0, 1, length)
HEX_CHARS = { 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'}
def convert_base(num, n): """Change a base 10 number to a base-n number.Supports up to base 16. """ new_num_string = '' current = num while current != 0: remainder = current % n if remainder > 9: remainder_string =HEX_CHARS[remainder] elif remainder >= 36: remainder_string ='('+str(remainder)+')' else: remainder_string =str(remainder) new_num_string =remainder_string+new_num_string current = current/n return new_num_string
Data Structures and Algorithms in Python
ISBN: 978-1118290279
1st edition
Authors: Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser