Convert roman numerals to numbers using Python

  • Roman Numerals are a number system used in ancient Rome. Numbers here are represented using a combination of letters. Modern style uses 7 symbols, each with different values. The largest number that can be written using these symbols are 3,999.

    Symbol Integer Value
    I 1
    V 5
    X 10
    L 50
    C 100
    D 500
    M 1000

    Numerals can be combined in different order to form numbers. See below roman numerals for numbers from 1 to 10 and some other 2 letter numerals for specific numbers.

    I = 1
    II = 2
    III = 3
    IV = 4
    V = 5
    VI = 6
    VII = 7
    VIII = 8
    IX = 9
    X = 10
    XL = 40
    XC = 90
    CD = 40
    CM = 900

    Some other examples:
    209 = CC + IX = CCIX
    93 = XC + III = XCIII
    1005 = M + V = MV
    1045 = M + CD + V = MCDV

  • Convert roman numerals to integer

    As seen above, we represent certain numbers using a single letter. And for some numbers, we require a combination of 2 letters. So to convert a roman numeral to integer number, the easiest way is to keep the specific values of these characters and then find the total.

    Sample code below. For bigger numbers, add the specific combinations to this group. Here we are storing the values as a tuple.

    Copied
    def numberFromRoman(romanNum):
        valuesTuple = ( (1, 'I'), (4, 'IV'), (5, 'V'), (9, 'IX'), (10, 'X'), (40, 'XL'), (50, 'L'),
                        (90, 'XC'), (100, 'C'), (400, 'CD'), (500, 'D'), (900, 'CM'), (1000, 'M')  )
        
        nlen = len(romanNum)
        i = 0
        finalNumber = 0
        while i < nlen:
            #Check for 2 letter combination first
            if ( nlen > i+1 and any(romanNum[i:i+2] in v for v in valuesTuple) ):
                strtoCheck = romanNum[i:i+2]
                i += 2
            else:
                strtoCheck = romanNum[i:i+1]
                i += 1
            
            number = next( s[0] for s in valuesTuple if (strtoCheck == s[1]) )
            finalNumber = finalNumber + number
    
        print(finalNumber)
    
    numberFromRoman('MMMCMXCIX')
    numberFromRoman('MMCMXLIX')
    
    Output:
      3999
      2949
Absolute Code Works - Python Topics