DiveIntoPython(十三)

DiveIntoPython(十三)

英文书地址:
http://diveintopython.org/toc/index.html

Chapter 14.Test-First Programming

14.1.roman.py,stage 1
example 14.1.roman1.py
#Define exceptions
class RomanError(Exception): pass
class OutOfRangeError(RomanError): pass
class NotIntegerError(RomanError): pass
class InvalidRomanNumeralError(RomanError): pass

def toRoman(n):
    """convert integer to Roman numeral"""
    pass

def fromRoman(s):
    """convert Roman numeral to integer"""
    pass

example 14.2.Output of romantest1.py against roman1.py


Running the script runs unittest.main(), which runs each test case, which is to say each method defined in each class within romantest.py. For each test case, it prints out the doc string of the method and whether that test passed or failed. As expected, none of the test cases passed.

14.2.roman.py,stage 2

example 14.3.roman2.py
#Define digit mapping
romanNumeralMap = (('M',  1000),
                   ('CM', 900),
                   ('D',  500),
                   ('CD', 400),
                   ('C',  100),
                   ('XC', 90),
                   ('L',  50),
                   ('XL', 40),
                   ('X',  10),
                   ('IX', 9),
                   ('V',  5),
                   ('IV', 4),
                   ('I',  1))

def toRoman(n):
    """convert integer to Roman numeral"""
    result = ""
    for numeral, integer in romanNumeralMap:
        while n >= integer:     
            result += numeral
            n -= integer
    return result

example 14.4.How toRoman works
If you're not clear how toRoman works, add a print statement to the end of the while loop:

        while n >= integer:
            result += numeral
            n -= integer
            print 'subtracting', integer, 'from input, adding', numeral, 'to output'

>>> import roman2
>>> roman2.toRoman(1424)
subtracting 1000 from input, adding M to output
subtracting 400 from input, adding CD to output
subtracting 10 from input, adding X to output
subtracting 10 from input, adding X to output
subtracting 4 from input, adding IV to output
'MCDXXIV'

example 14.5.Output of romantest2.py against roman2.py

Remember to run romantest2.py with the -v command-line flag to enable verbose mode.

14.3.roman.py,stage 3

example 14.6.roman3.py
def toRoman(n):
    """convert integer to Roman numeral"""
    if not (0 < n < 4000):                                            
        raise OutOfRangeError, "number out of range (must be 1..3999)"
    if int(n) <> n:                                                   
        raise NotIntegerError, "non-integers can not be converted"

    result = ""                                                       
    for numeral, integer in romanNumeralMap:
        while n >= integer:
            result += numeral
            n -= integer
    return result

example 14.7.Watching toRoman handle bad input
>>> import roman3
>>> roman3.toRoman(4000)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "roman3.py", line 38, in toRoman
    raise OutOfRangeError, "number out of range (must be 1..3999)"
OutOfRangeError: number out of range (must be 1..3999)
>>> roman3.toRoman(1.5)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "roman3.py", line 40, in toRoman
    raise NotIntegerError, "non-integers can not be converted"
NotIntegerError: non-integers can not be converted

example 14.8.Output of romantest3.py against roman3.py

14.4.roman.py,stage 4
Thanks to the rich data structure that maps individual Roman numerals to integer values, this is no more difficult than the toRoman function.

example 14.9.roman4.py
def fromRoman(s):
    """convert Roman numeral to integer"""
    result = 0
    index = 0
    for numeral, integer in romanNumeralMap:
        while s[index:index+len(numeral)] == numeral:
            result += integer
            index += len(numeral)
    return result

The pattern here is the same as toRoman. You iterate through your Roman numeral data structure (a tuple of tuples), and instead of matching the highest integer values as often as possible, you match the “highest” Roman numeral character strings as often as possible.

example 14.10.How fromRoman works
while s[index:index+len(numeral)] == numeral:
            result += integer
            index += len(numeral)
            print 'found', numeral, 'of length', len(numeral), ', adding', integer

>>> import roman4
>>> roman4.fromRoman('MCMLXXII')
found M of length 1 , adding 1000
found CM of length 2 , adding 900
found L of length 1 , adding 50
found X of length 1 , adding 10
found X of length 1 , adding 10
found I of length 1 , adding 1
found I of length 1 , adding 1
1972

example 14.11.Output of romantest4.py against roman4.py

14.5.roman.py,stage 5

example 14.12.roman5.py
#Define pattern to detect valid Roman numerals
romanNumeralPattern = '^M?M?M?(CM|CD|D?C?C?C?)(XC|XL|L?X?X?X?)(IX|IV|V?I?I?I?)$'

def fromRoman(s):
    """convert Roman numeral to integer"""
    if not re.search(romanNumeralPattern, s):                                   
        raise InvalidRomanNumeralError, 'Invalid Roman numeral: %s' % s

    result = 0
    index = 0
    for numeral, integer in romanNumeralMap:
        while s[index:index+len(numeral)] == numeral:
            result += integer
            index += len(numeral)
    return result

example 14.13.Output of romantest5.py against roman5.py
E:\book\opensource\python\diveintopython-5.4\py\roman\stage5>python romantest5.py
............
----------------------------------------------------------------------
Ran 12 tests in 0.328s

OK

你可能感兴趣的:(C++,c,python,C#,OpenSource)