Last active
February 20, 2017 21:54
-
-
Save cdcme/44aea73ad458aaee0f1e573cc8bba833 to your computer and use it in GitHub Desktop.
Roman numerals multiplication & division using the halve-and-double algorithm
This file contains 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 roman_to_arabic(roman_numeral): | |
""" | |
Note: Does not support shorthand notation yet! | |
Use IIII instead of IV, VIIII instead of IX, etc. | |
Args: | |
roman_numeral (str): the Roman numeral to convert | |
Returns: | |
int: the number, in Arabic number system | |
""" | |
try: | |
# guard example - what if a user provides shorthand? | |
# TODO: Implement shorthand conversions | |
if any([ | |
'IV' in roman_numeral, | |
'IX' in roman_numeral, | |
'XL' in roman_numeral, | |
'XC' in roman_numeral, | |
'CD' in roman_numeral, | |
'CM' in roman_numeral]): | |
print('Converter does not yet support shorthand! Use IIII instead of IV, VIIII instead of IX, etc. Your input was \'{0}\''.format(roman_numeral)) | |
return | |
roman_numerals = list(roman_numeral.upper()) | |
lookup_table = { | |
'I': 1, | |
'V': 5, | |
'X': 10, | |
'L': 50, | |
'C': 100, | |
'D': 500, | |
'M': 1000 | |
} | |
roman_values = [lookup_table[numeral] for numeral in roman_numerals] | |
return sum(roman_values) | |
except KeyError: | |
print('Looks like you have a character other than one of \'MDCLXVI\' in your argument, \'{0}\'!'.format(roman_numeral)) | |
except (AttributeError, TypeError) as error: | |
print('Looks like you need to provide an argument that is a string, like \'MCXVIII\'! Here\'s your error: {0}'.format(error)) | |
print(roman_to_arabic('MMXVIII')) | |
print(roman_to_arabic('MCCIX')) | |
print(roman_to_arabic('MCAXVI I~I')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment