carlodicelico
2/20/2017 - 9:46 PM

Roman numerals multiplication & division using the halve-and-double algorithm

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'))