python——罗马数字和阿拉伯数字的互相转换以及单元测试

(1)roman.py

# -*-coding:utf-8-*-
"""
this mode implements two functions, one implements the change from integer to roman numeral,
another  implements the opposite.
"""
"""
functional requirements:
(1)toroman应该能将1到3999之间的整数转换成对应的罗马数字
(2)toroman在遇到1到3999以外的整数应该失败
(3)toroman在遇到非整数时应该失败
(4)fromroman应该能将1到3999之间有效的罗马数字转换对应的成阿拉伯数字
(5)fromroman在遇到格式不正确的罗马数字应该失败
(6)toroman和fromroman应该满足完备性,即fromroman(toroman(n)) == n
(7)toroman应该返回的是全部大写的罗马数字
(8)fromroman应该只接收全部大写的罗马数字
"""
import re


class RomanError(Exception):  # 定义异常
    pass


class OutOfRangeError(RomanError):
    pass


class NotIntegerError(RomanError):
    pass


class InvalidRomanNumeralError(RomanError):
    pass

# define roman numeral map
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 numeral"""
    if not 0 < n < 4000:  # 当n=0或者n>3999再或者n为负数时
        raise OutOfRangeError
    if not int(n) == n:  # n为非整数时
        raise NotIntegerError

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

# 定义有效的正则表达式来检查罗马数字是否合格
romanNumeralPattern = r"^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
    result = 0
    index = 0
    for numeral, integer in romanNumeralMap:
        while s[index:index+len(numeral)] == numeral:
            result += integer
            index += len(numeral)
    return result

(2)roman.py模块的单元测试

# -*-coding:utf-8-*-
"""Unit test for roman.py"""
import roman
import unittest


index = 0  # 测试计数


# 正面测试
class KnownValuesT
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值