In [1]:
mapping = {'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000}
In [26]:
def roman_to_arabic(string):
out = 0
position = 0
while position < len(string):
val = mapping[string[position]]
if position == len(string)-1:
#-- goto ADD
out += val
position += 1
else:
nextval = mapping[string[position+1]]
if val == 1 and (nextval in [5, 10]):
#-- goto subtract
out += (nextval - val)
position += 2
elif val == 10 and (nextval in [50, 100]):
out += (nextval - val)
position += 2
elif val == 100 and (nextval in [500, 1000]):
out += (nextval - val)
position += 2
else:
out += val
position += 1
return out
In [ ]:
In [39]:
roman_to_arabic('MDCCCCVIIII')
Out[39]:
In [ ]: