Python Program for Converting Roman Numerals to Decimal Lying Between 1 to 3999


Roman numerals are known as the characters used in an arrangement of number notation based on the pre-Roman Roman system. All major symbols are covered in the section below. In this problem, we are given a string of Roman numerals and our task is to convert Roman numerals to decimals in the range of 1 to 3999

Here are some examples and explanations to help you better understand the problem.

Input

str = “MXCIX”

Output

1099

Explanation

M is the Roman representation of 1000,

XC is the Roman representation of 90,

IX is the Roman representation of 9.

Input

str = "II"

Output

2

Explanation

II is the Roman representation of 2.

Input

str = “XL”

Output

40

Explanation

XL is the Roman representation of 40.

Let's look at the primary Roman symbol before moving toward the approaches. Roman was entirely built around the symbol seen below: -

SYMBOL VALUE
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

Approach

As per the observation, the Roman numeral symbol follows the descending order to represent the numbers (e.g. M's come first, the C's, etc.). However, it also follows subtractive notation in certain situations to prevent 4 characters from continuously repeated (such as CCCC) in a row:

  • I comes before X or V to indicate one less. -> 4 represented in Roman as IV (one less than five), -> 9 represented in Roman as IX ( 1 less than 10)

  • X comes before C or L to indicate ten less. -> 40 represented in Roman as XL (ten less than fifty), -> 90 represented in Roman as XC (10 less than 100)

  • C comes before M and D to indicate 100 less -> 400 represented in Roman as CD (hundred less than five hundred) -> 900 represented in Roman as CM (hundred less than thousand)

To further understand the above method, let's look at the code below.

Example

Python Program to convert Roman Numerals to Decimal Lying Between 1 to 3999.

# Function is created to return a Roman symbol's value.
def value(ch):
   val = -1
   if(ch=='I'):
      val = 1
   if(ch=='V'):
      val = 5
   if(ch=='X'):
      val = 10
   if(ch=='L'):
      val = 50
   if(ch=='C'):
      val = 100
   if(ch=='D'):
      val = 500
   if(ch=='M'):
      val = 1000
   return val
def convertRomanToDecimal(str):
   decVal = 0
   i = 0
   n = len(str) # store the size of the string 
   while (i < n): 
      # store the numeric value of roman value str[i]
       current = value(str[i])
 
      # Check if i+1 charchter exists or not
       if (i + 1 < n): 
         # store the numeric value of roman value str[i+1]
         next = value(str[ i + 1 ]) 
         # Check which value is greater current or next
         if (current >= next): 
            # If current >= next add current
            # value to the variable decVal
            decVal = decVal + current
            # Increment the index of the string to point to the next char
            i = i + 1
         else:
            # If current<next add difference of next to current to the variable decVal
            decVal = decVal + next - current
            # Increment the index of the string to point to the next char
            i = i + 2
       else:
          decVal = decVal + current
          # Increment the index of the string to point to the next char
          i = i + 1 
   return decVal
print("The decimal Numeral form of the Roman Numeral is"),
print(convertRomanToDecimal("MXCIX"))

Output

The decimal Numeral form of the Roman Numeral is
1099

Time and Space Complexity

The time complexity of the above code is O(N), Where N is the size of the string. As no extra space is used in the code therefore the space complexity of the above code is O(1).

Approach 2

In this approach, we directly convert Roman to decimal by using the inbuilt module Roman. For that only need to install that Roman module using pip.

pip install roman

After successfully installing module roman, the conversion from roman to decimal is done by using the method fromRoman().

It receives the argument as a Roman value and outputs a decimal number.

Example

Below is a Python Program to convert Roman Numerals to Decimal implementing the above approach.

import roman
egFirst = roman.fromRoman("MXCIX")
egSecond = roman.fromRoman("II")
egThird = roman.fromRoman("XL")
print("Roman to Decimal conversions are:")
print(egFirst)
print(egSecond)
print(egThird)

Output

Roman to Decimal conversions are:
1099
2
40

Approach 3

Here uses a 're' module. The idea of this approach is simple, here we are using dictionary function of python that links Roman numerals with their corresponding decimal values. This programme accepts a Roman number as input and converts it to its corresponding decimal value.

Example

# Python Program to convert Roman Numerals to Decimal
import re
# Given string of Roman value
strRoman = 'MXCIX' 
# putting Roman numerals and their associated values in a dictionary
romanValue = {'M':1000, 'X':10, 'L':50, 'V':5, 'C':100, 'D':500, 'I':1} 
# Creating the variable decValue and assign zero to it
decValue = 0
n = len(strRoman) 
# Adding each value from the Roman Numeral string through a loop to the decValue variable
for i in range(n):
   if i > 0 and romanValue[strRoman[i]] >romanValue[strRoman[i-1]]:
      decValue += romanValue[strRoman[i]] - 2 * romanValue[strRoman[i-1]]
   else:
      decValue += romanValue[strRoman[i]] 
# Printing the Roman numeral in decimal form
print("The decimal Numeral form of the Roman Numeral", strRoman, "is")
print(decValue)

Output

The decimal Numeral form of the Roman Numeral MXCIX is
1099

Conclusion

In this tutorial, we have implemented a Python program For Converting Roman Numerals To Decimal Lying Between 1 to 3999. We have implemented three approaches. First with normal function, second with the Roman module, and third with re module (using a dictionary).

Updated on: 11-Jul-2023

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements