Created
September 21, 2016 15:51
-
-
Save ben-ng/550870e1b1122dbff435f3976707f07c to your computer and use it in GitHub Desktop.
Sample solution for converting roman numerals to integers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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