Python 带索引和缩进的平衡括号错误

Python balanced parenthesis error with index and indentation

我最近 python 和我 运行 在编写解决方案以检查一系列括号是否平衡时遇到了这个问题。我检查了关于缩进的不同帖子,但这似乎 help.It 没有给我一个 elif 行上 运行ge 错误的索引,自从它访问第一个和最后一个字符。任何帮助和反馈将不胜感激。

def nest_paren(s):
  if s == " ":
    return True
  elif len(s) % 2 == 1 or s[0] != '(' or s[-1] != ')':
    return False
  return nest_paren(s[1:-1])

nest_paren(s="(())")  # This should return True
nest_paren(s="((())") # This should return False

您的基本情况不正确。您需要处理空字符串,而不是其中包含 space 的字符串。

if s == " ": 更改为 if s == "": 应该可以。

我假设您只应该接受一组嵌套括号,形式为 (...(())...)。如果您还需要识别哪里有几组相邻的非嵌套平衡括号(如 (())()),您将需要更复杂的算法。这是通过对字符串进行迭代而不是递归来完成此操作的简单方法:

def nest_paren(s):
    open_count = 0
    for c in s:
        if c == '(':
            open_count += 1
        elif c == ')'
            open_count -= 1
            if open_count < 0:
                return False
        else:  # non-parenthesis character, you could ignore these instead
            return False
    return open_count == 0