Skip to content

Instantly share code, notes, and snippets.

@thedatadavis
Created August 25, 2020 23:44
Show Gist options
  • Save thedatadavis/c94e850c43c716b353d978a3fb8c4bb0 to your computer and use it in GitHub Desktop.
Save thedatadavis/c94e850c43c716b353d978a3fb8c4bb0 to your computer and use it in GitHub Desktop.
Converts Roman Numerals up to 50
new_ref = {
'I': 1,
'V': 5,
'X': 10,
'L': 50
}
def convert_roman(roman_numeral):
val = 0
skip_next = False
for letter in roman_numeral:
if skip_next:
skip_next = False
continue
current_idx = roman_numeral.index(letter)
if current_idx+1 < len(roman_numeral):
next_letter = roman_numeral[current_idx + 1]
else:
next_letter = ''
# If 'I' precedes one of the other letters
# decrement by 1, then add to value;
# then set the skip flag
if letter == 'I' and next_letter in ['V', 'X']:
val += (new_ref[next_letter] - 1)
skip_next = True
# If 'X' precedes 'L' subtract 10 from 50
# then add to value;
# then set the skip flag
elif letter == 'X' and next_letter in ['L']:
val += (new_ref[next_letter] - new_ref[letter])
skip_next = True
else:
val += new_ref[letter]
return val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment