python - 罗马到整数 python

标签 python python-3.x

我正在尝试用 python3 解决这个 python 问题,我的代码如下所示。

class Solution:
    def romanToInt(self, s: str) -> int:
        # Define integer value to each roman 
        rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50,
                  'C': 100, 'D': 500, 'M': 1000}
        # A list of integer values
        value = list(map(rom_val.get, s))
        # The subtracted new number
        new = 0
        # The converted integer number
        integer = 0
        # List to keep the checked roman
        checked = []
        for i, j in enumerate(value):
            if j > value[i+1] or j == value[i+1]:
                checked.append(j)
            if j < value[i+1]:
                new = value[i+1] - j
                checked.append(new)
        return sum(checked)

但是,我在第一个 if 语句中收到 IndexError: list index out of range。 尽管我知道这是一个相当简单的问题,但有些事情我不明白。 所以我有两个问题: 1.当然,为什么我会收到这个索引错误?我如何解决它? 2. 我解决这个问题的方法是否正确?

非常感谢。

最佳答案

这是一个不同的方法,5 行:

d = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}

def romanToInt(self, s):
    res, p = 0, 'I'
    for c in s[::-1]:
        res, p = res - d[c] if d[c] < d[p] else res + d[c], c
    return res

基本上,向后退,将每个字母加到结果中,除非较小的字母在较大的字母前面,在这种情况下是减法而不是加法。


注意:以下不是完整的解决方案,只是针对您在问题中提到的错误进行修复。您的算法中存在一个重大错误。

MCMXCIV 应该是 1994 但它返回 3099。这是因为您将 C 视为 100,将 M 视为 1000 但应该考虑 CM 作为 900。既然上面有一个解决方案,我会把它留给你作为练习。

您的代码存在问题,即使您到达最后一个索引,您也会检查 i + 1。您可以像这样修复它:

def romanToInt(s: str) -> int:
        # Define integer value to each roman 
        rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50,
                  'C': 100, 'D': 500, 'M': 1000}
        # A list of integer values
        value = list(map(rom_val.get, s))

        # List to keep the checked roman
        checked = []
        for i, j in enumerate(value):
            if i == len(value) - 1:
                checked.append(j)
            elif j >= value[i+1]:
                checked.append(j)
            elif j < value[i+1]:
                checked.append(value[i+1] - j)

        print(checked)
        return sum(checked)

print(romanToInt("LVIII"))

我还让您的代码更加简洁,删除了不必要的变量。主要变化只是检查它是否是 value 中的最后一个索引。

关于python - 罗马到整数 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61719161/

相关文章:

python - 如何动态打开json文件?

python - int 字典与 string 字典以减少大小

Python:tkinter从类中删除对象并使其不可见

python - 正则表达式查找后面不跟某些字符的数字

python - 导入错误 : DLL load failed when importing win32clipboard in application frozen with cx_Freeze

python-3.x - Python编译器将 print 函数中的 10^-16 添加到答案中

Python 延迟加载属性不适用于类方法

python - 多处理仅运行第一行代码

python - 在 pytest 中运行单个文件,该文件是 PEP 420 隐式命名空间包中的模块

python - 操作系统错误: [WinError 193] %1 is not a valid Win32 application (LibTiff)