将罗马数字转换为整数的Python程序中出错

rnmwe5a2  于 4个月前  发布在  Python
关注(0)|答案(2)|浏览(68)
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号线

dffbzjpn

dffbzjpn1#

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

字符串
这个错误是因为当i等于len(s)-1时,你试图在循环中访问s[i+1]。此时,s[i+1]超出了字符串的边界,导致IndexError。

piv4azn7

piv4azn72#

一个简单的解决方案是改变:

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

相关问题