列表索引中的索引在Python中,但索引在范围内如何?

发布于 2025-02-01 11:04:53 字数 550 浏览 2 评论 0原文

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

最长的validparentes(“)(()())(“)

我的代码以找到正确形成的括号数量 但是在第二个循环中,我遇到了这样的错误

在 最长的无伴hishess(“)(”)(())() if(s [i] ==“(”):indexError:列表索引不在范围

,但列表不超出范围

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执手闯天涯 2025-02-08 11:04:53

您有一个动态变量(LEN(S)),用作您的上限。快速检查是在您弹出后发布Len的打印声明。第一个POP发生在足够的早期,以至于您的原始循环仍然有效,但是第二次弹出时,您的len(s)= 5,然后您尝试访问s [5],因为我将其递增至5。界限以来,这两个弹出量已将您的字符串减少到此时的0、1、2、3、4。

您在这里有两个选项,您可以删除pop,以使索引不会在循环中更改,也可以修改逻辑(我的第一个想法是一个wire循环,可以增加或不同时弹出)。

edit :我意识到约书夫就在我做之前就对修复程序进行了评论。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文