Python罗马数字和阿拉伯数字互转


class RomanAlaboOp(object):

    @classmethod
    def alabo2roman(cls, alabo):
        '''''
        阿拉伯转罗马
        '''
        alabo = int(alabo)
        num_list = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
        str_list = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
        res = ''
        for i in range(len(num_list)):
            while alabo >= num_list[i]:
                alabo -= num_list[i]
                res += str_list[i]
        return res

    @classmethod
    def roman2alabo(cls, roman):
        '''''
        罗马转阿拉伯
        '''
        define_dict = {'I' :1 ,'V' :5 ,'X' :10 ,'L' :50 ,'C' :100 ,'D' :500 ,'M' :1000}
        if roman == '0':
            return 0
        else:
            res = 0
            for i in range(0 ,len(roman)):
                if i == 0 or define_dict[roman[i]] <= define_dict[roman[i - 1]]:
                    res += define_dict[roman[i]]
                else:
                    res += define_dict[roman[i]] - 2 * define_dict[roman[i - 1]]
            return res


if __name__ == '__main__':
    print(f'2 to {RomanAlaboOp.alabo2roman(2)}')                    # 2 to II
    print(f'56 to {RomanAlaboOp.alabo2roman(56)}')                  # 56 to LVI
    print(f'1359 to {RomanAlaboOp.alabo2roman(1359)}')              # 1359 to MCCCLIX
    print(f'XII to {RomanAlaboOp.roman2alabo("XII")}')              # XII to 12
    print(f'VIII to {RomanAlaboOp.roman2alabo("VIII")}')            # VIII to 8
    print(f'MDCXVIII to {RomanAlaboOp.roman2alabo("MDCXVIII")}')    # MDCXVIIII to 1619
    

你可能感兴趣的:(Python,python,开发语言,numpy)