Skip to content

Instantly share code, notes, and snippets.

@ben-ng ben-ng/roman.py
Created Sep 21, 2016

Embed
What would you like to do?
Sample solution for converting roman numerals to integers
def convert(char):
return {
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}.get(char)
def romanToInteger(input):
# Turns each character of the input into an integer
# e.g. "IV" becomes [1, 5] after this
converted = map(convert, list(input))
# Call the helper function with the converted list,
# and a starting sum of 0
return _romanToInteger(converted, 0)
def _romanToInteger(input, lastSum):
# If there are no characters left, we are done, so return the last sum
if len(input) == 0:
return lastSum
# If there are at least two characters left, and the first character
# is smaller than the second character, then subtract the first from
# the second, add the result to lastSum, and recurse on the remainder
# of the input
elif len(input) > 1 and input[0] < input[1]:
return _romanToInteger(input[2:], lastSum + input[1] - input[0])
# Otherwise, add the first character of the input, and recurse on
# the remainder of the input
else:
return _romanToInteger(input[1:], lastSum + input[0])
print(romanToInteger('IV'))
print(romanToInteger('X'))
print(romanToInteger('XVI'))
print(romanToInteger('DC'))
print(romanToInteger('MCD'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.