List index out of range Error in python ,but index is in range how is it?


def longestValidParentheses(si):
    for _ in range(0,len(si)):
    for i in range(0,len(s)-1):
     if (s[i]=="("):
      for j in range(0,len(s)):
        if (s[j]==")"):
    return cnt


This my code to find how many correctly formed parenthesis
but in the second loop I AM getting an error like this

Traceback (most recent call last): File "F:/", line 17, in

longestValidParentheses(")(())()") File "F:/", line 9, in longestValidParentheses
if (s[i]=="("): IndexError: list index out of range

but list is not out of range


You have a dynamic variable (len(s)) used as your upper bound on your range. A quick check is to throw a print statement of len(s) after you pop. The first pop occurs early enough that your original loop is still valid, but the second time you pop you have len(s) = 5, and then you try to access s[5] as i is incremented to 5. This is out of bounds since the two pops have reduced your string to 0, 1, 2, 3, 4 at this point.

You have two options here, you can remove the pop so that the indices do not change in the loops, or you can modify the logic (my first thought would be a while loop that increments or pops not both).

Edit: I realize JoshuaF commented the fix just before I did.

Answered By – Michael Williamson

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.