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

问题描述 投票:0回答:1
    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-3.x index-error
1个回答
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。

© www.soinside.com 2019 - 2024. All rights reserved.