问题描述
我基本上是在尝试有关leetcode的一些练习问题。我有一些索引问题。有谁知道我为什么收到这个回复?
def romanToInt(self,s: str) -> int:
roman = list(s)
num = 0
for i in range(len(s)
if roman[i] == "I" and roman[i+1] == "V":
num = num + 4
elif roman[i] == "I" and roman[i+1] == "X":
num = num + 9
elif roman[i] == "X" and roman[i+1] == "L":
num = num + 40
elif roman[i] == "X" and roman[i+1] == "C":
num = num + 90
elif roman[i] == "C" and roman[i+1] == "D":
num = num + 400
elif roman[i] == "C" and roman[i+1] == "M":
num = num + 900
elif roman[i] == "I":
num = num + 1
elif roman[i] == "V":
num = num + 5
elif roman[i] == "X":
num = num + 10
elif roman[i] == "L":
num = num + 50
elif roman[i] == "C":
num = num + 100
elif roman[i] == "D":
num = num + 500
elif roman[i] == "M":
num = num + 1000
解决方法
在for循环中到达迭代结束时,您仍在检查下一个不存在的元素。
if roman[i] == "I" and roman[i+1] == "V":
num = num + 4
基本上,当“ i”位于数组/列表的末尾时,当您尝试访问“ i + 1”时,您将越过列表的末尾。
以下由随机戴维斯提供:考虑“ I”的情况。当您在当前的实现中进行检查时,最终将寻找下一个不存在的元素。
额外的位:python中的字符串可以超过“长度”的末尾,然后回绕。
stringy = "hello world"
print(stringy[-1]) //This will show "d"
print(stringy[11]) //this will show "h"