Skip to content

Instantly share code, notes, and snippets.

@cdcme
Last active February 20, 2017 21:54
Show Gist options
  • Save cdcme/44aea73ad458aaee0f1e573cc8bba833 to your computer and use it in GitHub Desktop.
Save cdcme/44aea73ad458aaee0f1e573cc8bba833 to your computer and use it in GitHub Desktop.
Roman numerals multiplication & division using the halve-and-double algorithm
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