A while ago, I posted part of this source code, which would calculate the decimal value of Roman numerals. So, I got inspired, and added the much more challenging Arabic to Roman version.
I spent like four hours on this… grr.
def arabic_to_roman(number):
roman = {1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M'}
values = roman.keys()
values.sort()
for value in values[:-1]:
next = values[values.index(value) + 1]
if number%next is not 0 and number%next is not 4:
return arabic_to_roman(number-(number%next))+(roman[value]*(number%next/value))
elif number%next is 4:
return roman[value]*(next-(number%next))+arabic_to_roman(next+number-number%next)
return roman[1000]*(number/1000)
def roman_to_arabic(numerals):
total = 0
values = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
prev_value = 0
for char in numerals:
if values[char] > prev_value:
total -= prev_value
else:
total += prev_value
prev_value = values[char]
total += prev_value
return total
if __name__ == '__main__':
for i in range(10000):
if i!=roman_to_arabic(arabic_to_roman(i)):
print i