Python程序中将罗马数字转换为整数时出错(我找到了解决方案,但显然我现在无法删除它)

问题描述 投票:0回答:2
    def romanToInt(self, s: str) -> int:
        num = 0
        lst = ["I","V","X","L","C","D","M"]
        dict = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
        for i in range(len(s)):
            if lst.index(s[i]) >= lst.index(s[i+1]) or i == len(s)-1:
                num = num + dict[s[i]]
            else:
                num = num - dict[s[i]]
        return num
        

这是我将罗马数字转换为整数的代码

程序正在触发此错误

IndexError:字符串索引超出范围

6号线

python python-3.x index-error
2个回答
0
投票
    def romanToInt(self, s: str) -> int:
        num = 0
        lst = ["I", "V", "X", "L", "C", "D", "M"]

 ## I changed the var name dict to dictionary because using dict as a variable name 
 ## can lead to confusion and potential issues, as it may override the
 ## built-in dict type within the scope of your function.
        dictionary = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}

        for i in range(len(s) - 1):
            if lst.index(s[i]) >= lst.index(s[i + 1]):
                num += dictionary[s[i]]
            else:
                num -= dictionary[s[i]]

        num += dictionary[s[-1]]

        return num

错误是因为当

s[i+1]
等于
i
时,您试图在循环中访问
len(s)-1
。此时,
s[i+1]
超出了字符串的范围,导致 IndexError。


0
投票

解决方案的一个简单修复方法是更改:

if lst.index(s[i]) >= lst.index(s[i+1]) or i == len(s)-1:
                                           ^^^^^^^^^^^^^

if i == len(s)-1 or lst.index(s[i]) >= lst.index(s[i + 1]):
   ^^^^^^^^^^^^^

因为你首先检查

i == len(s) - 1
,如果它是True,它不会执行其他部分,你不会得到索引错误。


作为替代方案,您可以在字典中包含这些特殊数字(例如

'IV'
'IX'
'XL'
'XC'
'CD'
'CM'
)并重写为:

roman_map = {
    "I": 1,
    "V": 5,
    "X": 10,
    "L": 50,
    "C": 100,
    "D": 500,
    "M": 1000,
    "IV": 4,
    "IX": 9,
    "XL": 40,
    "XC": 90,
    "CD": 400,
    "CM": 900,
}


def roman_to_int(s: str) -> int:
    i = 0
    result = 0
    while i < len(s):
        if i + 1 < len(s) and s[i : i + 2] in roman_map:
            result += roman_map[s[i : i + 2]]
            i += 2
        else:
            result += roman_map[s[i]]
            i += 1
    return result


print(roman_to_int("III"))     # 3
print(roman_to_int("CDXLIII")) # 443
  • 尝试遵循 Python 的命名约定(
    romanToInt
    )。
  • 不要隐藏内置名称(
    dict
    )。
© www.soinside.com 2019 - 2024. All rights reserved.