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号线
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。