In order to convert a roman number into the decimal representation of a natural number \(x > 0\), the following algorithm can be used:
def roman2dec(z): ''' convert roman number into decimal number ''' lastD = 0 value = 0 for i in range (0, len(z)): digit = z[i].upper() if digit == 'M': nextD = 1000 elif digit == "D": nextD = 500 elif digit == "C": nextD = 100 elif digit == "L": nextD = 50 elif digit == "X": nextD = 10 elif digit == "V": nextD = 5 elif digit == "I": nextD = 1 else: raise Exception("Wrong roman digit: "+digit)
if lastD < nextD:
value -= lastD
else:
value += lastD
lastD = nextD
value += lastD
return value
x = "DCCXLIX" r = roman2dec(x) print(x + " = " + str(r))