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

Issue

def longestValidParentheses(si):
    cnt=0
    s=[]
    for _ in range(0,len(si)):
        s.append(si[_])
    print(s[6])
    for i in range(0,len(s)-1):
     print(i)
     if (s[i]=="("):
      for j in range(0,len(s)):
        if (s[j]==")"):
          cnt+=2
          s.pop(j)
          break
    print(cnt)   
    return cnt

longestValidParentheses(")(())()")

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:/yy.py", line 17, in

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

but list is not out of range

Solution

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.