Search code examples
pythonroman-numerals

Easy Leetcode question, I don't understand what I'm doing wrong


I'm beginner in coding and I am working on some easy leetcode questions along the way. The question is converting roman numerals to integers and when I run this code, it says the "string index out of range". Rather than looking for other answers, I wanted to understand what I did wrong. I appreciate the help!

s = "CCXLVII"

roman_dict = {
    'C' : 100,
    'L' : 50,
    'X' : 10,
    "V" : 5,
    "I" : 1
}

temp = 0

for i in range(len(s)):
    if roman_dict[s[i]] > roman_dict[s[i+1]] and i + 1 < len(s): #string index out of range
        temp = temp - roman_dict[s[i]]
    else:
        temp = temp + roman_dict[s[i]]

Solution

  • You just have to swap the order of the conditionals:

    Change:

    if roman_dict[s[i]] > roman_dict[s[i+1]] and i + 1 < len(s):
    

    To:

    if i + 1 < len(s) and roman_dict[s[i]] > roman_dict[s[i+1]]:
    

    This makes it so that the boundary check is done before attempting to access the i+1 index. Python will short-circuit the condition as soon as i + 1 >= len(s) is true