美文网首页生活不易 我用python
罗马数字与阿拉伯数字相互转换

罗马数字与阿拉伯数字相互转换

作者: burglar | 来源:发表于2018-08-01 17:19 被阅读0次
    #!/usr/bin/env python3
    '''
    thousands - 0 to 3 Ms
     hundreds - 900 (CM),400 (CD),0-300 (0 to 3 Cs),
                or 500-800 (D,followed by 0 to 3 Cs)
         tens - 90 (XC),40 (XL),0-30 (0 to 3 Xs)
                or 50-80 (L,followed by 0 to 3 Xs)
         ones - 9 (IX),4 (IV),0-3 (0 to 3 Is)
                or 5-8 (V,fowllowed by 0 to 3 Is)
    
    the range of the number need to be converted is 1-3999
    '''
    import re
    
    
    def isRoman(num):
        pattern = '^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})'
        if re.search(pattern, num):
            return 1
        else:
            return 0
    
    
    def arabic2roman(num):
        if num > 3999 or num < 1:
            print('num is out of range (1-3999)')
            return
        dict = {
            0: ('', 'M', 'MM', 'MMM'),
            1: ('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'),
            2: ('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'),
            3: ('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX')
        }
    
        roman = ''
        roman += dict[0][num // 1000 % 10]
        roman += dict[1][num // 100 % 10]
        roman += dict[2][num // 10 % 10]
        roman += dict[3][num % 10]
        return roman
    
    
    def roman2arabic(roman):
        if isRoman(roman) == 0:
            print('it is not a valid roman number !')
            return
        num = 0
        dict = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
        for i in range(len(roman)-1):
            if dict[roman[i]] < dict[roman[i+1]]:
                num -= dict[roman[i]]
            else:
                num += dict[roman[i]]
        return num+dict[roman[-1]]
    
    

    相关文章

      网友评论

        本文标题:罗马数字与阿拉伯数字相互转换

        本文链接:https://www.haomeiwen.com/subject/glmrvftx.html