python 罗马数字乘法和除法使用half-and-double算法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 罗马数字乘法和除法使用half-and-double算法相关的知识,希望对你有一定的参考价值。

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

以上是关于python 罗马数字乘法和除法使用half-and-double算法的主要内容,如果未能解决你的问题,请参考以下文章

仅使用O(lgβ)乘法和除法将β位整数转换为数字数组

使用乘法和除法从小到大的字节序-MIPS汇编

题目:大整数乘法除法,楼梯走法,数组中不同数字,超过一半数字(好)

高精度乘法和除法

高精度加法,减法,乘法,除法

如何将数字的最后3位转换为0