Search code examples
pythonindex-error

How to access the next index without going out of bounds?


I'm working with lists and I'm trying to access the next value in an if statement like this: if((lst[i+1] != 'V') or (lst[i+1] != 'X')):. But as you can see, this is super prone to errors. And it did cause an IndexError.

What is the best way to call the next item in a list without trying to breach the list's size?

Basically, its a LeetCode assignment asking to convert Roman numbers to regular numbers. This is my full code:

class Solution:
    def romanToInt(self, s: str) -> int:
        lst = list(s)
        counter = 0

        for i in range(len(lst)):

            if(lst[i] == 'I'):
                if((lst[i+1] != 'V') or (lst[i+1] != 'X')):
                    counter += 1
                elif(lst[i+1] == 'V'):
                    counter += abs(1-5)
                elif(lst[i+1] == 'X'):
                    counter += abs(1-10)

            if(lst[i] == 'V'):
                if(lst[i-1] != 'I'):
                    counter += 5
                else:
                    counter += abs(1-5)

            if(lst[i] == 'X'):
                if((lst[i+1] != 'L') or (lst[i+1] != 'C')):
                    counter += 10
                elif(lst[i+1] == 'L'):
                    counter += abs(10-50)
                elif(lst[i+1] == 'C'):
                    counter += abs(10-100)

            if(lst[i] == 'L'):
                if(lst[i-1] != 'X'):
                    counter += 50
                else:
                    counter += abs(10-50)

            if(lst[i] == 'C'):
                if((lst[i+1] != 'D') or (lst[i+1] != 'M')):
                    counter += 100
                elif(lst[i+1] == 'D'):
                    counter += abs(100-500)
                elif(lst[i+1] == 'M'):
                    counter += abs(100-1000)

            if(lst[i] == 'D'):
                if(lst[i-1] != 'C'):
                    counter += 500
                else:
                    counter += abs(100-500)

            if(lst[i] == 'M'):
                if(lst[i-1] != 'C'):
                    counter += 1000
                else:
                    counter += abs(100-1000)


        return counter

I don't want any deep help. I just want to know how to come across this one issue as I couldn't find anything relative to conditional statements.


Solution

  • In you code you need to replace your for loop:

    for i in range(len(lst))
    

    with

    for i in range(len(lst))
    

    to avoid going out of range since you are accessing the lst lst at both i+1, and i-1 in your loop.

    For another example of converting Roman numerals to decimals check out: https://www.geeksforgeeks.org/converting-roman-numerals-decimal-lying-1-3999/