25+ Python Roman to Decimal Converters

This post contains total of 25+ Python Roman to Decimal Converter examples with source code. All the roman to decimal converters are made using Python programming language.

You can use the source code of these programs for educational use with credits to the original owner.

Related Posts

Click a Code to Copy it.

1. By Mikhail Gorchanyuk

Made by Mikhail Gorchanyuk. Enter the roman number you want to convert to decimal in ‘x=’MCMLXXXIV’ Line. ( Source )

'''
Input format:
 A string containing a number encoded in the Roman numeral system.  It is guaranteed that the number is less than 4000.
We will use the option in which the numbers 4, 9, 40, 90, 400 and 900 are written as a subtraction from a larger number of a smaller one: IV, IX, XL, XC, CD and CM, respectively.'''
 
 
#x = input()
x='MCMLXXXIV'
d = {'I' :1, 'V':5, 'X' :10, 'L' :50, 'C' :100,       'D' :500, 'M' :1000}
r=0
p=0
for i in x[::-1]:
  if d[i] >= p:
    r+=d[i]
    p=d[i] 
  else:
    r-=d[i]
print(r)

2. By CΓ©pagrave

Made by CΓ©pagrave. Enter roman number in line ‘r = ‘MCMLXXVI’ ( Source )

'''
takes roman number and converts it to decimal
'''

r = 'MCMLXXVI'

d = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, "V":5, 'I': 1}
 
print(sum([(1-2*(d[a]<d[b]))*d[a]for a,b in zip(r,r[1:])])+d[r[-1]])

# unpacked
def r2n(r):
    s = 0
    for a,b in range(len(r)-1):
        # comparing to the right neighbor:
        if d[a]<d[b]:
            val = -d[a]
        else:
            val = d[a]
    # right-most element:
    s += d[r[-1]]
    return s

3. By LLuthfiY

Made by LLuthfiY. Simple python program to convert roman into decimal. ( Source )

z= input()
x= z.lower()
hasil=0
hasil1=0

for i in range(len(z)):
    hasil=hasil1
    if x[i]=='i':
        f=1
    elif x[i]=='v':
        if x[i-1]=='i' and i-1 != -1:
            f=3
        else:
            f=5
    elif x[i]=='x':
        if x[i-1]=='i' and i-1 != -1:
            f=8
        else :
            f=10
    elif x[i]=='l':
        if x[i-1]=='x' and i-1 != -1:
            f=30
       
        else :
            f=50
    elif x[i]=='c':
        if x[i-1]=='x' and i-1 != -1:
            f=80
      
        else :
            f=100
    elif x[i]=='d':
        if x[i-1]=='c' and i-1 != -1:
            f=300
      
        else :
            f=500
    elif x[i]=='m':
        if x[i-1]=='c' and i-1 != -1:
            f=800
           
        else :
            f=1000
    else :
        f=0
    hasil=hasil1+f
    q=hasil
    hasil1=hasil    
print('your roman number is :' + z)   
print('decimal number is:'+str(q))

4. By Wade

Made by Wade. ( Source )

x = input()
def solution(x):
    x = list(x)
    a = 0
    dict = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
    for i in range(len(x)):
        if i >= 1:
            if dict[x[i]] > dict[x[i-1]]:
                a+= dict[x[i]]-dict[x[i-1]]
                a-= dict[x[i-1]]
            else:
                a += dict[x[i]]
        else:
            a+= dict[x[i]]
    return a
print(solution (x))

5. By Stefano De Angelis

Made by Stefano De Angelis. ( Source )

r = list(input())
 
values = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
cn = 0
n = 0
l = len(r)

while cn < len(r):
 if l >= 2:
  if values[r[cn + 1]] > values[r[cn]]:
   n += values[r[cn + 1]] - values[r[cn]]
   cn += 2
   l -= 2
  else:
   n += values[r[cn]]
   cn += 1
   l -= 1
 else:
  n += values[r[cn]]
  cn += 1
  l -= 1
  
print(n)

#Version: Alpha
#You can ran into some bugs 'cause the program is uncomplete.
#For example IIV (not a real roman number) is considered as 1 + 4. Working on this.

6. By Christian Barrieta

Made by Christian Barrieta. Simple program to convert roman to decimal. ( Source )

dec = str(input("Roman Numeral Input to Decimal:"))
Roman = {'I':'1','V':'5','X':'10','L':'50','C':'100','D':'500','M':'1000'}
add = 0
min = 0
count = 0

while(count!=len(dec)):
    if(count<len(dec)-1 and int(Roman[dec[count]]) < int(Roman[dec[count+1]])):
        min = min + int(Roman[dec[count]])
    else:
        add = add + int(Roman[dec[count]])
    count+=1
print('\n{} ==> {}'.format(dec,add-min))

7. By Maria

Made by Maria. ( Source )

#Roman number to decimal

def roman2decimal(s):
    dict = (('IV', 4), ('IX', 9), ('XL', 40), ('XC', 90), ('CD', 400), ('CM', 900), ('I', 1), ('V', 5), ('X', 10), ('L', 50), ('C', 100), ('D', 500), ('M', 1000))
    n = 0
    for i in dict:
        if s.find(i[0])>=0:
            n += i[1] * s.count(i[0])
            s = s.replace(i[0], '')
    return n


print(roman2decimal(input()))

8. By Mike Buttery

Made by Mike Buttery. ( Source )

# Roman to decimal
# Enter a valid roman numeral

def romantodec(roman):
    roman = roman.upper()
    decimal = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1}
    # validate string
    inp = set([*roman])
    rn = set(decimal.keys())
    if inp.issubset(rn):
        result = 0
        for i in range(len(roman)):
            val = decimal[roman[i]]
            if i + 1 < len(roman) and decimal[roman[i + 1]] > val:
                result -= val
            else:
                result += val
        return roman, result
    else:
        raise ValueError("Not a valid Roman numeral")


r, d = romantodec(input())
print("Roman: {}\nDecimal: {}".format(r, d))

9. By NILANJAN CHAKRABORTY

Made by NILANJAN CHAKRABORTY. ( Source )

class Roman:
    def rom_to_dec(self,st):
        RN={
            'I':1,
            'V':5,
            'X':10,
            'L':50,
            'C':100,
            'D':500,
            'l':1000
        }
        i=0
        num=0
        while i<len(st):
            if i+1<len(st) and st[i:i+2] in RN:
                num=num+ RN[st[i:i+2]]
                i=i+2
            else:
                num=num+RN[st[i]]
                i=i+1
        print("The decimal conversion is ",num)


x=input()
obj1= Roman()
obj1.rom_to_dec(x)

10. By X-1

Made by X-1. ( Source )

"""Rules to obey when using Roman numerals(or, at least, my interpretation:

    - when the larger number is behind the smaller numbers, you add them all up

    - when the larger number is in front, you do the larger number minus the smaller numbers

"""


"""Only numbers you can use:

   I(1), V(5) ,X(10) ,L(50) ,C(100), D(500), and M(1000)(in ascending order).

"""


"""My plan:

    - Create an array mapping the values from 1 to 1000(most likeley in a dictionary) to their equalvelent letters

    - Let the user enter their desired numbers.

    - optimise to accomodate invalid input

    - Do the appropriate calculations

    - give the result

"""


#currently the code works without error, but some nubers are off.

rNumerals = {"I":1,"IV":4, "V":5, "IX":9, "X":10,"XL":40, "L":50,"LX":90, "C":100, "CL":150, "D":500, "CM":900, "M":1000}
lNumerals = [key for key in rNumerals]#this allows us to access and compare the letters properly. note that there are seven letters total in the array.
#print(rNumerals[lNumerals[3]])allows me to output the array using the letters stored in the array.
rNumeralExceptions = {"IV":4,"IX":9,"XL":40,"LX":90, "CL":150,"CM":900}



def linearSearch(arr, value): #this will be performed on each value that the user has entered, for example in "XII" the linear search will be performed three times, returning 1,1,1 in an array
    for index in range(0,len(arr)):
        if arr[index] == value:
            return 1
    return -1

def getNumber(numeralInput,lNumerals, enteredArr): #gets input and checks if it's valid.


    enteredArr = []

    loop = True

    while loop:
        del enteredArr[:]
        
        numeralInput = str(input("Enter the desired roman numeral: "))
        
        for index in range(0,len(numeralInput)):
            enteredArr.append(linearSearch(lNumerals, numeralInput[index]))
            
        for x in range(0,len(enteredArr)):
                       if enteredArr[x] != 1:
                           #print("index is not valid.")
                           loop = True
                           
                               
                       else:
                           #print("index is valid.")
                           loop = False
    return numeralInput

def calculations(lNumerals,rNumerals,numeralInput, enteredArr,rNumeralExceptions):

    total = 0
    lRNumeralExceptions = [key for key in rNumerals]
    
    #add iteration algoithim here.
    
    #three possible outcomes when iterating through the array:
    
     #an index of the input matches a key from the roman numeral's dictionary.
      #add the key value of the input to the total
     
     #an index + the next index is equal to a key from the roman numeral's dictionary(requires checking whether you are at the end of the array to avoid index errors).
        #add the key value of the two combined indexes to the total.
        
    #the index matches none, which has already been handled by the previous getNumber function.
        
    #get the input as a number from the previous array.
    
    number = getNumber(numeralInput, lNumerals, enteredArr)
   
    numberLength = len(number) #- 1 #still battling with this indx error.
    lNumeralLength = len(lNumerals) #- 1
    rNumeralExceptionsLength = len(lRNumeralExceptions)
    
    for index in range(0, lNumeralLength):
        for index2 in range(0, rNumeralExceptionsLength):
            for index3 in range(numberLength):
                
                #checks if the index is equal to the array of exceptions(I
                
                lRNumeralExceptions[index2]
                
                if number[index3] != lRNumeralExceptions[index2]:
                    total += rNumerals[number[index3]]
                    
    
            #For now, the total should be 0.
            """
            if number[index2] != lNumerals[index] and index2 != numLength:
              if number[index2] + number[index2 + 1] == lNumerals[index]:
                
                print(number[index2] + number[index2 + 1])
                total += rNumerals[number[index2] + number[index2 + 1]]
                continue
              
            elif number[index2] == lNumerals[index]:
              total += rNumerals[number[index2]]
            
            """
            
            #here, we might to make an array filled with only special case values so that input like VI don't hit this loop(V, for example, will always find an equivelent value.)
                
           
            
            
    
    return total
     
            

        

enteredArr = []
numeralInput = ""
print("The total is {}".format(calculations(lNumerals, rNumerals, numeralInput, enteredArr, rNumeralExceptions)))


11. By Cybercharm

Made by Cybercharm. Roman to Decimal converter using Python. Enter roman number in last line. ( Source )

# Python program to convert Roman Numerals
# to Numbers

# This function returns value of each Roman symbol


def value(r):
	if (r == 'I'):
		return 1
	if (r == 'V'):
		return 5
	if (r == 'X'):
		return 10
	if (r == 'L'):
		return 50
	if (r == 'C'):
		return 100
	if (r == 'D'):
		return 500
	if (r == 'M'):
		return 1000
	return -1


def romanToDecimal(str):
	res = 0
	i = 0

	while (i < len(str)):

		# Getting value of symbol s[i]
		s1 = value(str[i])

		if (i + 1 < len(str)):

			# Getting value of symbol s[i + 1]
			s2 = value(str[i + 1])

			# Comparing both values
			if (s1 >= s2):

				# Value of current symbol is greater
				# or equal to the next symbol
				res = res + s1
				i = i + 1
			else:

				# Value of current symbol is greater
				# or equal to the next symbol
				res = res + s2 - s1
				i = i + 2
		else:
			res = res + s1
			i = i + 1

	return res


# Driver code
print("Integer form of Roman Numeral is"),
print(romanToDecimal("MCMIV"))

12. By Roofpipe

Made by Roofpipe. ( Source )

def romanToInt(s):
		translations = {
			"I": 1,
			"V": 5,
			"X": 10,
			"L": 50,
			"C": 100,
			"D": 500,
			"M": 1000
		}
		number = 0
		s = s.replace("IV", "IIII").replace("IX", "VIIII")
		s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
		s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
		for char in s:
			number += translations[char]
		print(number)
		
romanToInt('MCMIV')

13. By Samane

Made by Samane. Convert Roman to Decimal and vice versa. ( Source )

from collections import OrderedDict

digits = {
    'M': 1000,
    'D': 500,
    'C': 100,
    'L': 50,
    'X': 10,
    'V': 5,
    'I': 1
}

romans = OrderedDict()
romans[1000] = "M"
romans[900] = "CM"
romans[500] = "D"
romans[400] = "CD"
romans[100] = "C"
romans[90] = "XC"
romans[50] = "L"
romans[40] = "XL"
romans[10] = "X"
romans[9] = "IX"
romans[5] = "V"
romans[4] = "IV"
romans[1] = "I"


def toDigit(roman):
    final = 0
    string = roman[::-1]
    for i in range(0, len(string)-1):
        if i == len(string)-1:
            break
        value1 = digits[string[i].upper()]
        value2 = digits[string[i+1].upper()]
        if i == 0:
            final = value1
        if value1 <= value2:
            final += value2
        elif value1 > value2:
            final -= value2

    return final


def toRoman(num):
    num = int(num)
    for r in romans.keys():
        x, y = divmod(num, r)
        yield romans[r] * x
        num -= y
        if num > 0:
            toRoman(num)
        else:
            break


def main():
    while True:
        number = input("1. Roman to Integer\n2. Integer to Roman \n")
        if number == '1':
            num = input("Enter your Roman numeral: ")
            if len(num) == 1:
                print("Integer " + num.upper() + " : " + str(digits[num.upper()]) + "\n\n")
            else:
                print("Integer " + num.upper() + " : " + str(toDigit(num)) + "\n\n")

        elif number == '2':
            num = str(input("Enter an Integer number: "))
            print("Roman " + num + " : " + "".join([a for a in toRoman(num)]) + "\n\n")
main()

14. By Rnzfan

Made by Rnzfan. ( Source )

#! usr/bin/env python
"""Roman to Decimal Number converter"""

_romanvalue = { "I": 1,
                "V": 5,
                "X": 10,
                "L": 50,
                "C": 100,
                "D": 500,
                "M": 1000 }

def roman(romannumber):
    decimalnumber = 0
    global _romanvalue
    for i in range(len(romannumber)-1):
        if _romanvalue[romannumber[i]] < _romanvalue[romannumber[i+1]]:
            decimalnumber -= _romanvalue[romannumber[i]]
        else:
            decimalnumber += _romanvalue[romannumber[i]]
    decimalnumber += _romanvalue[romannumber[-1]]
    return decimalnumber

def main():
    print("Welcome to this fun Roman to Decimal Number converter\n")
    romaninput = input("Please type your roman number here: ")
    print(f"The decimal number is: {roman(romaninput)}\n")
    return

if __name__ == "__main__":
    main()

15. By Andrei-Br

Made by Andrei-Br. ( Source )

""" I = 1; V = 5; X = 10; L = 50; C = 100; D = 500; M = 1000"""


class NumberNotValid(Exception):
    pass


def user_input():
    while True:
        try:
            user_num = input('Enter a Roman numeral between 1 and 3,999: ')
            char_check = [char for char in user_num]
            for char in char_check:
                if char not in ['I', 'V', 'X', 'L', 'C', 'D', 'M']:
                    raise NumberNotValid
            else:
                return user_num

        except NumberNotValid:
            print("Your number is not valid. Try again, using only the "
                  "following characters: 'I', 'V', 'X', 'L', 'C', 'D', 'M'.\n")


class RomanToDecimal:
    def __init__(self):
        self.num = user_input()
        self.rom_val = {'I': 1,
                        'V': 5,
                        'X': 10,
                        'L': 50,
                        'C': 100,
                        'D': 500,
                        'M': 1000}

    def calc(self):
        int_val = 0
        for i in range(len(self.num)):
            if i > 0 and self.rom_val[self.num[i]] \
                         > self.rom_val[self.num[i-1]]:
                int_val += self.rom_val[self.num[i]] \
                           - 2 * self.rom_val[self.num[i-1]]
            else:
                int_val += self.rom_val[self.num[i]]
        print(self.num, '=', int_val)


def main():
    RomanToDecimal().calc()
    input()


if __name__ == '__main__':
    main()

16. By jacobrogers603

Made by jacobrogers603. Converting a roman numeral formatted number to base ten integer.( Source )

# Jacob Rogers
# 2-27-2022



def romanToInt(s : str) -> int:
        
    romanDict = {'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000, 'Z' : 0}
        
    stringLength = len(s)
#   Add a ternimating character that means zero to every string so we can always check forwards for subtraction cases, even at the end of the string.
    s = s + 'Z'
    total = 0
    i = 0
        
    while i < stringLength:
            
        if s[i] == 'I':
            if s[i+1] == 'V':
                total = total + 4
                i += 2
                continue
            elif s[i+1] == 'X':
                total = total + 9
                i += 2
                continue
            else:
                total = total + romanDict.get(s[i])
                i += 1
                
        elif s[i] == 'V':
            total = total + romanDict.get(s[i])
            i += 1
                
        elif s[i] == 'X':
            if s[i+1] == 'L':
                total = total + 40
                i += 2
                continue
            elif s[i+1] == 'C':
                total = total + 90
                i += 2
                continue
            else:
                total = total + romanDict.get(s[i])
                i += 1
                    
        elif s[i] == 'L':
            total = total + romanDict.get(s[i])
            i += 1
            
        elif s[i] == 'C':
            if s[i+1] == 'D':
                total = total + 400
                i += 2
                continue
            elif s[i+1] == 'M':
                total = total + 900
                i += 2
                continue
            else:
                total = total + romanDict.get(s[i])
                i += 1
                    
        elif s[i] == 'D':
            total = total + romanDict.get(s[i])
            i += 1
                
        elif s[i] == 'M':
            total = total + romanDict.get(s[i])
            i += 1
                
    return total

go = True

while go:
    
    print("Roman Numeral to base ten, Roma Victa.")
    s = input('Enter a Roman Numeral IN ALL CAPS to see its base ten number: ')

    print(romanToInt(s))

    i = input('press q to quit, or anykey and then enter to continue. ')
    if i == 'q':
        go = False

17. By Hallessandro

Made by Hallessandro. ( Source )

def RomanToDecimal(number):
    final_number = 0
    for x in range(len(number)):
        try:
            result = next_numb(number[x], number[x+1])
            if(result != 0):
                if(x-1 < 0):
                    final_number += result
                else:
                    final_number += previous_numb(number[x], number[x - 1])
            else:
                final_number += 0
        except IndexError:
            try:
                final_number += previous_numb(number[x], number[x - 1])
            except IndexError:
                final_number += convert(number[x])

    return final_number

def next_numb(number, next):
    if convert(next) > convert(number):
        return 0
    else:
        return convert(number)

def previous_numb(number, previous):
    if(convert(previous) < convert(number)):
        return convert(number) - convert(previous)
    else:
        return convert(number)

def convert(value):
    if (value == "I"):
        return 1
    elif (value == "V"):
        return 5
    elif (value == "X"):
        return 10
    elif (value == "L"):
        return 50
    elif (value == "C"):
        return 100
    elif (value == "D"):
        return 500
    elif (value == "M"):
        return 1000

18. By devika-be

Made by devika-be. Python Program to Convert Roman Numbers to Decimals. ( Source )

tallies = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000,
    # specify more numerals if you wish
}

def RomanNumeralToDecimal(romanNumeral):
    sum = 0
    for i in range(len(romanNumeral) - 1):
        left = romanNumeral[i]
        right = romanNumeral[i + 1]
        if tallies[left] < tallies[right]:
            sum -= tallies[left]
        else:
            sum += tallies[left]
    sum += tallies[romanNumeral[-1]]
    return sum

19. By Archana appikatla

Made by Archana appikatla. ( Source )

tallies = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000,
    # specify more numerals if you wish
}

def RomanNumeralToDecimal(romanNumeral):
    sum = 0
    for i in range(len(romanNumeral) - 1):
        left = romanNumeral[i]
        right = romanNumeral[i + 1]
        if tallies[left] < tallies[right]:
            sum -= tallies[left]
        else:
            sum += tallies[left]
    sum += tallies[romanNumeral[-1]]
    return sum

20. By naemazam

Made by naemazam. ( Source )

def encoder(num):
    roman,s,decimal= ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"],"",[1000,900,500,400,100,90,50,40,10,9,5,4,1]
    for i in range(13):
           while num >= decimal[i]:
                  num -= decimal[i]
                  s += roman[i]
    return s

def decoder(r):
    k=r
    if r=="":return "Don't leave the input blank"
    roman,s= {"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},0
    while r!="":
        if r[:2] in roman:a,r=r[:2],r[2:]
        elif r[0] in roman:a,r=r[0],r[1:]
        else: return "Enter proper Decimal/Roman number as input"
        s+=roman[a]
    return s if encoder(int(s))==k else "Not a valid Roman Numeral"
    
a=input()
try:print(encoder(int(a)))
except:print(decoder(a.upper())) 

21. By andcarnivorous

Made by andcarnivorous. ( Source )

def romantodecimals():
    
    data = input("Insert Roman Number >>>")
    counter = 0

    ### I-IX ####

    for x in range(len(data)):
        if data[x] == "I":
            if x == (len(data)-1) or data[x+1] not in ("X", "V"):
                counter += 1
            elif data[x+1] == "V":
                counter += 0
            elif data[x+1] == "X":
                counter += 0
        if data[x] == "V":
            if x == 0 or data[x-1] != "I":
                counter += 5
            elif data[x-1] == "I":
                counter += 4

        #### X #####         
        if data[x] == "X":

            if x == (len(data)-1):
                if len(data) == 1:
                    counter += 10

                elif data[x-1] not in ("I"):
                    counter += 10

                elif data[x-1] == "I":
                    counter += 9
            elif data[x+1] == "L":
                counter += 0
            elif data[x+1] == "C":
                counter += 0

            elif x == 0:
                if data[x+1] not in ("L","C"):
                    counter += 10
                elif data[x+1] in ("C"):
                    counter += 0

            elif data[x+1] not in ("L", "C") and data[x-1] not in ("I"):
                counter += 10

                
        #### L ####
        if data[x] == "L":
            if x == 0 or data[x-1] != "X":
                counter += 50
            elif data[x-1] == "X":
                counter += 40


        #### C #####
        if data[x] == "C":

            if x == 0:
                if data[x+1] not in ("D","M"):
                    counter += 100

            elif x == (len(data)-1):
                if len(data) == 1:
                    counter += 100

                elif data[x-1] not in ("X"):
                    counter += 100

                elif data[x-1] == "X":
                    counter += 90
            elif data[x+1] == "D":
                counter += 0

            elif data[x-1] in ("X"):
                counter += 90
            elif data[x+1] in ("D", "M"):
                counter += 0
            else:
                counter += 100

                
        ### D ####                
        if data[x] == "D":
            if x == 0 or data[x-1] != "C":
                counter += 500
            elif data[x-1] == "C":
                counter += 400

        if data[x] == "M":
            if x == 0 or data[x-1] != "C":
                counter += 1000
            elif data[x-1] == "C":
                counter += 900

        else:
            print("")
            
        print("adding: ", counter)
    print(counter)


while True:
    converter()

22. By Sichkar valentyn

Made by Sichkar valentyn. ( Source )

# File: Roman_to_decimal_number_system.py
# Description: Conversion Roman number to decimal number system
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 Valentyn N Sichkar
# github.com/sichkar-valentyn
#
# Reference to:
# [1] Valentyn N Sichkar. Conversion Roman number to decimal number system // GitHub platform [Electronic resource]. URL: https://github.com/sichkar-valentyn/Roman_number_to_decimal_number (date of access: XX.XX.XXXX)




# Implementing the task
# Converting Roman number system to decimal number system
# By using regular expressions

# Importing library 're'
import re

# Creating a pattern for finding following numbers in the string: 4, 9, 40, 90, 400, 900
# By using '|' we say which groups of symbols to look for
pattern_1 = r'IV|IX|XL|XC|CD|CM'

# Inputting string in Roman number system
string = input()  # 'MCMLXXXIV'

# Finding all inclusions according to the pattern_1 and put them into the list
all_inclusions = re.findall(pattern_1, string)  # ['CM', 'IV']

# Deleting found inclusions in the string
for i in range(len(all_inclusions)):
    string = re.sub(all_inclusions[i], r'', string)  # At the end we'll receive 'MLXXX'

# Creating a pattern for finding following numbers in the string: 1, 5, 10, 50, 100, 500, 1000
# By using '|' we say which groups of symbols to look for
pattern_2 = r'I|V|X|L|C|D|M'

# Finding all inclusions according to the pattern_2 and adding them to the list
all_inclusions += re.findall(pattern_2, string)  # We'll receive ['CM', 'IV', 'M', 'L', 'X', 'X', 'X']

# Creating a dictionary for conversion
d = {'I': 1,
     'V': 5,
     'X': 10,
     'L': 50,
     'C': 100,
     'D': 500,
     'M': 1000,
     'IV': 4,
     'IX': 9,
     'XL': 40,
     'XC': 90,
     'CD': 400,
     'CM': 900}

# Converting to decimal number system
# Going through all elements of the list and finding the values in the dictionary
# After the appropriate values were found it is needed just to add them all together
n = 0
for x in all_inclusions:
    n += d[x]

print(n)

23. By Jopt

Made by Jopt. Simple roman to decimal converter with python and tkinter.. ( Source )

import os

data = {
    'I' : 1,
    'V' : 5,
    'X' : 10,
    'L' : 50,
    'C' : 100,
    'D' : 500,
    'M' : 1000
}

def clear():
    os.system('clear')

def convert( number ):
    decimal = 0
    x = 0
    while x < len(number):
        v1 = data.get(number[x])
        if x + 1 < len(number):
            v2 = data.get(number[x+1])
            if v1 >= v2:
                decimal += v1
                x += 1
            else:
                decimal = decimal + v2 - v1
                x += 2
        else:
            decimal += v1
            x += 1
    print("Conversion equals to:", decimal)

while True:
    print("----------------------------------------")
    print("\tRoman to Decimal Converter")
    print("\t\tby Jopt05")
    print("----------------------------------------")

    print("")

    roman_number = input("Insert your roman number = ")

    for char in roman_number:
        if char not in data:
            print(char ,"is not valid. Try again")
            break
    

    convert( roman_number )
    break

24. By YasiruLak

Made by YasiruLak. ( Source )

tallies = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000,
    # specify more numerals if you wish
}


def RomanNumeralToDecimal(romanNumeral):
    sum = 0
    for i in range(len(romanNumeral) - 1):
        left = romanNumeral[i]
        right = romanNumeral[i + 1]
        if tallies[left] < tallies[right]:
            sum -= tallies[left]
        else:
            sum += tallies[left]
    sum += tallies[romanNumeral[-1]]
    return sum

25. By limeiralucas

Made by limeiralucas. ( Source )

from __future__ import annotations

class RomanNumber:
    def __init__(self, symbol: str) -> None:
        self.symbol = symbol.upper()
    
    def __repr__(self) -> str:
        return self.symbol

    def __eq__(self, obj: RomanNumber) -> bool:
        return obj.symbol == self.symbol

    def to_decimal(self) -> int:
        decimal_to_roman_map = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000
        }
        
        converted_number = 0
        number_at_right = None
        for char in self.symbol[::-1]:
            number = decimal_to_roman_map.get(char)
            
            if number_at_right and number_at_right > number:
                converted_number += number * -1
            else:
                converted_number += number
            number_at_right = number
        
        return converted_number

    @staticmethod
    def _decimal_to_roman_symbol(number: int) -> str:
        decimal_to_roman_map = {
            1: "I", 
            5: "V", 
            10: "X", 
            50: "L", 
            100: "C", 
            500: "D", 
            1000: "M", 
        }

        return decimal_to_roman_map.get(number)

26. By wkrzyzanowski

Made by wkrzyzanowski. ( Source )

from app_utils import *


def decimal_to_roman(user_input):
    validate_decimal_input(user_input)

    allowed_numerals = list(roman_characters_map.keys())
    allowed_numerals.reverse()  # Sort values from high to low
    user_input_number = int(user_input)

    result = ''

    while user_input_number != 0:
        for numeral in allowed_numerals:
            if user_input_number >= numeral:
                user_input_number = user_input_number - numeral
                result += str(roman_characters_map.get(numeral))
                break

    return result


def roman_to_decimal(user_input):
    validate_roman_input(user_input)

    switched_map = {y: x for x, y in roman_characters_map.items()}

    allowed_literals = list(roman_characters_map.values())
    allowed_literals.reverse()

    result = 0
    tmp_roman = ''
    tmp_dec = 0

    while user_input != '':
        for input_char in user_input:
            tmp_roman += input_char
            if tmp_roman in allowed_literals and tmp_dec < switched_map.get(tmp_roman):
                tmp_dec = switched_map.get(tmp_roman)
            else:
                result += tmp_dec
                user_input = user_input[len(tmp_roman) - 1:]
                tmp_roman = ''
                tmp_dec = 0
                break

    return result


def main():
    args = parse_app_arguments()

    if args.todecimal is False and args.toroman is False:
        print("One of either flags are required: [-dec] [--todecimal] and [-rom] [--toroman]. See more with --help.")
        exit(1)
    elif args.todecimal is True and args.toroman is True:
        print("Both options: [-dec] [--todecimal] and [-rom] [--toroman] are not allowed. Choose one.")
        exit(1)
    elif args.toroman is True:
        result = decimal_to_roman(args.input)
        print(f"{args.input} => {result}")
    elif args.todecimal is True:
        result = roman_to_decimal(args.input)
        print(f"{args.input} => {result}")


# Run program
main()