Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
def roman_numerals_to_decimal(strParam):
# code goes here
roman_numerals_order = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
roman_numerals_mapping = {
roman_numerals_order[0]: 1,
roman_numerals_order[1]: 5,
roman_numerals_order[2]: 10,
roman_numerals_order[3]: 50,
roman_numerals_order[4]: 100,
roman_numerals_order[5]: 500,
roman_numerals_order[6]: 1000,
}
def is_substractable(last, first):
# roman_numerals = roman_numerals_mapping.keys() # order not guaranteed
diff = roman_numerals_order.index(last) - roman_numerals_order.index(first)
if diff == 1 or diff == 2:
return True
if len(strParam) == 1:
return roman_numerals_mapping[strParam]
retval = 0
chars = list(reversed(list(strParam)))
skip_next = False
for i, char in enumerate(chars):
if skip_next:
skip_next = False
continue
if i+1 < len(chars): # still have one char left
next_char = chars[i+1]
if is_substractable(char, next_char):
retval += roman_numerals_mapping[char] - roman_numerals_mapping[next_char]
skip_next = True
else:
retval += roman_numerals_mapping[char]
else:
retval += roman_numerals_mapping[char]
return retval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment