-1

I basically am trying out some practice questions on leetcode. I am having an issue with some indexing issues. Does anyone know why I get this response?

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
John Chen
  • 11
  • 4

1 Answers1

1

When you get to the end of the iteration in the for loop, you are still checking the next element which doesn't exist.

 if roman[i] == "I" and roman[i+1] == "V":
            num = num + 4

Basically when "i" is at the end of the array/list you're going past the end of the list when you try and access "i+1".

Courtesy of Random Davis below: consider the case of "I". when you check this with your current implementation you'll end up looking for the next non-existent element.

Extra bit: strings in python can go past the end of the "length" and just wrap back around.

stringy = "hello world"
print(stringy[-1]) //This will show "d"
print(stringy[11]) //this will show "h"
  • 1
    This is especially noticeable if you call `romanToInt` with just `"I"`. There's only one item in the list, and yet the function is trying to index `roman[i+1]`, which is past the bounds of the string, so the code doesn't make sense right now. – Random Davis Sep 23 '20 at 22:08
  • @RandomDavis Thanks for the input, that's an excellent test case. I added that bit to my answer – Jack Arnold Sep 23 '20 at 22:15
  • So basically I need to do it in reverse so it doesn't go over the index number? – John Chen Sep 23 '20 at 22:20